Limit amount of file uploads with carrierwave

前端 未结 1 1352
粉色の甜心
粉色の甜心 2021-01-07 10:10

I have a User Model and have a Image model with carrierwave.

I want to limit the amount of images an user could upload because I have a second form where the user go

相关标签:
1条回答
  • 2021-01-07 10:25

    I guess your model is somehow similar to that :

    class User
      has_many :photos
    end
    
    class Photo
      belongs_to :user
      mount_uploader :file, PhotoUploader
    end
    

    So that means you could simply add a validation on the user on how many photos it can have. You can see that post : Limit number of objects in has_many association

    You would end up with something like that in your photo model :

    LIMIT = 3
    
    validate do |record|
      record.validate_photo_quota
    end
    
    def validate_photo_quota
      return unless self.user
      if self.user.photos(:reload).count >= LIMIT
        errors.add(:base, :exceeded_quota)
      end
    end
    
    0 讨论(0)
提交回复
热议问题