Rails 3 ActiveRecord 预先加载范围 [英] Rails 3 ActiveRecord eager loading of scope
本文介绍了Rails 3 ActiveRecord 预先加载范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮帮我.我有一些与其他模型有很多关联的模型.例如:个人资料 => has_many :statistics在统计模型内部,我有一些范围:
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.
现在我只能使用
User.profiles.includes(:statistics)
谢谢.
推荐答案
如此处所述: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)
这篇关于Rails 3 ActiveRecord 预先加载范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文