limit the number of objects returned in a has_many

前端 未结 3 1911
迷失自我
迷失自我 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 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

提交回复
热议问题