Limit number of objects in has_many association

后端 未结 4 403
情书的邮戳
情书的邮戳 2020-12-02 09:38

I have an album which has_many photos. A counter_cache setup updates the photos_count column in the album table. How do I limit the number of photos for an album?

4条回答
  •  一生所求
    2020-12-02 10:19

    Use a validation hook:

    class Album
      has_many :photos
      validate_on_create :photos_count_within_bounds
    
      private
    
      def photos_count_within_bounds
        return if photos.blank?
        errors.add("Too many photos") if photos.size > 10
      end
    end
    
    class Photo
      belongs_to :album
      validates_associated :album
    end
    

提交回复
热议问题