在的has_many返回的对象数量限制 [英] limit the number of objects returned in a has_many
本文介绍了在的has_many返回的对象数量限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何限制在一个有很多关系,返回的行数?例如:
How can I limit the number of rows returned in a has many relationship? For example:
class User < ActiveRecord::Base
has_many :photos
end
我希望能够做的:
I want to be able to do:
User.includes(:photos => {:limit => 8}).all
这显然是行不通的,但一些使用这一功能。我是否需要写出来的SQL自己?
This obviously doesnt work, but something with this functionality. Do I need to write out the SQL myself?
在此先感谢!
编辑: 我不希望限制的关联,只是查询结果。因此,用户可能有上千张照片,我只希望前3回。
I dont want to limit the association, just the query results. So a User might have a thousand photos, I only want the top 3 returned.
推荐答案
只需添加一个限制选项给的has_many关联:
Just add a limit option to the has_many association:
class User < ActiveRecord::Base
has_many :photos, :limit => 8
end
修改
根据您的需要:
class User < ActiveRecord::Base
has_many :all_photos, :class_name => "Photo"
has_many :photos, :limit => 8
end
注意:改变阶级在all_photos协会将class_name
这篇关于在的has_many返回的对象数量限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文