Ishu
Ishu

Reputation: 638

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

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

Any help is appreciated.

Thanks.

Upvotes: 5

Views: 1612

Answers (2)

Veger
Veger

Reputation: 37915

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.

Upvotes: 4

Farrel
Farrel

Reputation: 2381

Post.all( :include => { :city => :state })

Upvotes: 9

Related Questions