Rails 3 ActiveRecord eager loading of scope

╄→尐↘猪︶ㄣ 提交于 2019-12-18 02:28:08

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/7937759/rails-3-activerecord-eager-loading-of-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!