On Aug 5, 9:48 am, M- Ryan <[email protected]> wrote:
> Hello everyone,
>
> I would like to eager load scoped records to avoid queries executed in a
> loop (huge performance impact).
>
> The "scoped" part is what is giving me a hard time.

Can you define a scope at class level, instead of defining a method?

scope :recent, where ["published_at >= ?", 2.days.ago]

Then when you later do

article.comments.recent

the join/include clauses should be chained together *first*, resulting
in max one query per article.

Jeff

> I'm using Rails3 RC.
>
> Does anyone have any idea how I can do it?
>
> Here is a test case : we have an "Article" and a "Comment" Activerecord
> models,
>
> article has many comments
> comment belongs to article
>
> Comment has a scope defined like this (app/models/comment.rb) :
>
> ----------------------------------------------
>
> def recent
>   where ["published_at >= ?", 2.days.ago]
> end
>
> ----------------------------------------------
>
> In the ArticlesController (app/controllers/comments_controller.rb) :
>
> ----------------------------------------------
>
> def index
>   @articles = Article.includes(:comments)
> end
>
> ----------------------------------------------
>
> In the view (haml) (app/views/articles/index.html.haml):
>
> ----------------------------------------------
>
> - @articles.each do |article|
>   = article.title
>   - article.comments.each do |comment|
>     = comment.body
>
> ----------------------------------------------
>
> this works fine and no query is executed when accessing the comments for
> each articles ("includes" call in the controller handled the eager
> loading).
>
> But if you try to display only the recent comments for each article :
>
> ----------------------------------------------
>
> - @articles.each do |article|
>   = article.title
>   - article.comments.recent.each do |recent_comment|
>     = recent_comment.body
>
> ----------------------------------------------
>
> Now a query is executed for every article in order to fetch it's recent
> articles.
>
> What can I write (presumably in the "include" call) to get the eager
> loading to work in this situation ?
>
> Cheers,
>
> M-Ryan
> --
> Posted viahttp://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to