Fetching second level model with rails active record
I have a relationship in which a post belongs to the city which inturn belongs to a state like:
class Post < ActiveRecord::Base
belongs_to :city
end
class City < ActiveRecord::Base
belongs_to :state
end
Now i want to find all the posts along with the their cities and the states to which the belong to. I wrote the following query to fetch the posts with their cities but out of ideas on how to fetch the corresponding state with the city in the same find开发者_如何学编程er:
@post = Post.find :all, :include => [:city]
Any help is appreciated.
Thanks.
Post.all( :include => { :city => :state })
Rails will handle this for you, thanks to the belongs_to relation this information is fetched automatically.
@posts = Post.find(:all)
@posts
now contains the logic to fetch the city
and city.state
details for all the returns posts.
If you are planning to use all these details you should eager load them, with :include => { :city => :state }
as Farrel and mckeed stated.
Note: to make it work the other way around (and it is also supposed good Model defining behaviour) you should add the has_many
or has_one
association as well. See the Association Basics Guide.
精彩评论