views:

146

answers:

2

Hello,

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 finder:

@post = Post.find :all, :include => [:city]

Any help is appreciated.

Thanks.

+4  A: 

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.

Veger
As your link explains, if you are going to access all the associated records, you should eager-load them with `:include` like in Farrel's answer. Otherwise when you loop through `@posts`, every time you ask for the post's city or state, it will do another database fetch, leading to much slower code.
mckeed
You are completely right, thanks for pointing out. I have updated the answer with this information.
Veger
+4  A: 
Post.all( :include => { :city => :state })
Farrel