In my Rails app I have a fairly standard has_many relationship between two entities. A Foo
has zero or more Bars
; a Bar
belongs to exactly
Personally, if each Bar is dependent on a Foo, option #2 makes more sense. For example, if Foo is a blog and Bar is a post, it is far more logical to access a particular post at example.bloghosting.com/blog/1/post/2
than example.bloghosting.com/post/21
.
Do do this with the latest version of Rails:
class Food < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
Then, in the Rails router (/config/routes.rb):
map.resources :foos do |foo|
foo.resource :bars
end
For more information, see Rails Routing from the Outside In and the Rails API Documentation.