开发者

Eager Loading on existing Objects

In rails you can eager load associations when you create a new object like this:

@person = Person.find(params[:id], :include => {:flights => :plane})

However, i sometimes already have the @person object and then want to eager开发者_开发问答 load the associations. There does not seem to be any 'rails' way to do this. I am looking for something like this basically:

@person = Person.find(params[:id])
...
@person.include({:flights => :plane})

Background is, I have a before filter that already creates the @object without associations. But in some actions if i do not eager load the associations i will generate a lot of singular queries. And doing

@person = Person.find(params[:id])
...
@person = Person.find(params[:id], :include => {:flights => :plane})

seems like a bit of a waste.


In Rails 2, you can use scoped to create the appropriate query:

 @person.flights.scoped(:include => :plane)

In Rails 3, you can do this the Rails 3 Way:

 @person.flights.include(:plane)

You might consider adding the :include option to your has_many declaration so it is included by default when loaded from Person:

 has_many :flights, :include => :plane

You can alternately add a default scope to Flight, causing any query on Flight to include its plane:

 default_scope :include => :plane


Just use @person.flights and set a default_scope on flights to include plane.
Or in your Person model: has_many :flights, :include => plane

You should switch to Rails3, check out Active Record Queries in Rails 3 to see why!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜