Limit amount of file uploads with carrierwave

房东的猫 提交于 2019-12-18 18:26:27

问题


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


来源:https://stackoverflow.com/questions/14238297/limit-amount-of-file-uploads-with-carrierwave

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!