limit the number of objects returned in a has_many

前端 未结 3 1908
迷失自我
迷失自我 2020-12-16 18:07

How can I limit the number of rows returned in a has many relationship? For example:

class User < ActiveRecord::Base
  has_many :photos
end
相关标签:
3条回答
  • 2020-12-16 18:56

    You can put a :limit on the actual has_many declaration.

    class User < ActiveRecord::Base
      has_many :photos, :limit => 8
    end
    
    0 讨论(0)
  • 2020-12-16 19:03

    Just add a limit option to the has_many association:

    class User < ActiveRecord::Base
      has_many :photos, :limit => 8
    end
    

    EDIT

    According to your needs:

    class User < ActiveRecord::Base
      has_many :all_photos, :class_name => "Photo"
      has_many :photos, :limit => 8
    end
    

    note: changed 'class' to 'class_name' in the all_photos association

    0 讨论(0)
  • 2020-12-16 19:07

    You don't have to hard code the limit in the model. You can call @user.photos.limit(8). You can also call @user.photos.scoped to get a scope object that does lazy loading. The thing returned from @user.photos may look very, very much like an Array, but it's not - it lies to you!

    See http://apidock.com/rails/ActiveRecord/Associations/CollectionProxy for an interesting trip into the rabbit hole - the thing you get back is delegating pretty much all of the standard object inspection calls (class, singleton_class, methods, method, etc.) to an Array object, but it's delegating a certain set of calls to an ActiveRecord::Associations::* object. That's why if you call @user.photos.method(:<<) it will tell you it's using #<Method: Array#<<>, but it's not actually using that - it's using the one in ActiveRecord::Associations::CollectionProxy!

    0 讨论(0)
提交回复
热议问题