Limit number of objects in has_many association

后端 未结 4 404
情书的邮戳
情书的邮戳 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:04

    How about adding a custom validation method to the Photo model?

      LIMIT = 50
    
      validate_on_create do |record|
        record.validate_quota
      end
    
      def validate_quota
        return unless self.album
        if self.album.photos(:reload).count >= LIMIT
          errors.add(:base, :exceeded_quota)
        end
      end
    

提交回复
热议问题