限制has_many中返回的对象数
如何限制多个关系中返回的行数? 例如:
class User < ActiveRecord::Base has_many :photos end
我希望能够做到:
User.includes(:photos => {:limit => 8}).all
这显然不起作用,但具有此function的东西。 我是否需要自己编写SQL?
提前致谢!
编辑:我不想限制关联,只是查询结果。 所以一个用户可能有一千张照片,我只想要返回前三名。
只需为has_many关联添加限制选项:
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’
您不必对模型中的限制进行硬编码。 你可以调用@user.photos.limit(8)
。 您还可以调用@user.photos.scoped
来获取延迟加载的范围对象。 从@user.photos
返回的东西可能看起来非常非常像一个Array
,但它不是 – 它对你而言!
请访问http://apidock.com/rails/ActiveRecord/Associations/CollectionProxy ,了解兔子洞的有趣之旅 – 您获得的内容是委派几乎所有标准对象检查调用( class
, singleton_class
, methods
, method
,等)到一个Array
对象,但是它将一组调用委托给一个ActiveRecord::Associations::*
对象。 这就是为什么如果你调用@user.photos.method(:<<)
它会告诉你它正在使用#
,但它实际上并没有使用它 - 它正在使用ActiveRecord::Associations::CollectionProxy
!
你可以对实际的has_many
声明设置一个:limit
。
class User < ActiveRecord::Base has_many :photos, :limit => 8 end