Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 ActiveRecord eager loading of scope

Help me please. I have some model which has_many association with other model. For example: profile => has_many :statistics And inside of statistic model I have some scope:

scope last_ten, limit(10).order('online desc')

And question is how can I use eager load for this scope? I don't need every record of statistics for profile. Only scoped.

Now I can use only

 User.profiles.includes(:statistics)

Thanks.

like image 977
ValeriiVasin Avatar asked Oct 29 '11 08:10

ValeriiVasin


1 Answers

As explained here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

It's better to define a custom relation:

class Profile < ActiveRecord::Base
  has_many :most_recent_stats, :class_name => 'Statistic', :order => 'online DESC', :limit => 10
  ...
end

User.profiles.includes(:most_recent_stats)
like image 70
apneadiving Avatar answered Sep 28 '22 08:09

apneadiving