ActiveRecords Eager Loading

Beta Beta wrote:


I am doing an eager loading in ruby on rails using below statement ------------------------      Article.find(:all, :include => [:asset, :vote],                   :conditions=>"assets.parent_id is null",                   :order=>"stat_final_ranking desc", :limit=>20) --------------------------------------- the above statement resulted in this expensive query. After indexing, it take about 3 seconds to execute. (before indexing it is about 25 seconds)

One way forward with this non-caching option would be to only load the votes of the current user. This can be done with a trick that dynamically sets the :conditions option on the vote association.

so, what I plan to do it is to cache the expensive query without including vote table      Article.find(:all, :include => [:asset],                   :conditions=>"assets.parent_id is null",                   :order=>"stat_final_ranking desc", :limit=>20)

then later combine it with vote table which is different for each user.

Is the method to cache the expensive query the right approach?

Also, I have another question how to combine @articles and @vote after getting it from database.    @articles= Article.find(:all, :include => [:asset],                   :conditions=>"assets.parent_id is null",                   :order=>"stat_final_ranking desc", :limit=>20) with    @votes = Vote.find(:all, :conditions=> "user_id" ....

You want the votes to be hashed by article id, which the above would not give you unless you hashed it after retrieval.

The alternative is to do an Article query like your original one, but leaving out the asset association, and, for speed, only selecting the id of the article model. Now you can include the user_id condition because don't care if the articles the user hasn't voted for are dropped.

Id-only selection would however require use of plugins that allow use of the find :select option in combination with eager loading of the votes.