限制 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
我希望能够做到:
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?
提前致谢!
我不想限制关联,只是查询结果.所以一个用户可能有一千张照片,我只想要返回前三张.
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"更改为class_name"
这篇关于限制 has_many 中返回的对象数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文