Limit amount of file uploads with carrierwave

2019-02-11 07:51发布

问题:

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 goes to upload de images and I want him to able to upload only 3 images. Is there an elegante solution for this? Or do I have to make a custom validator that counts the amount of images the user as?

回答1:

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