用carrierwave限制文件上传量 [英] Limit amount of file uploads with carrierwave
问题描述
我有一个用户模型,并有一个带有载波的图像模型。$ b
$ b
我想限制用户可以上传的图像数量,因为我有第二种形式用户去上传图片,我希望他只能上传3张图片。有没有elegante解决方案呢?或者我必须做一个自定义的验证,计算用户的图像数量?
解决方案我猜你的模型是以某种方式类似于:
class User
has_many:photos
end
class Photo
belongs_to:user
mount_uploader:file,PhotoUploader
end
<所以这意味着你可以简单地在用户上添加一个验证它可以有多少照片。你可以看到这个帖子:限制has_many关联中的对象数量
LIMIT = 3
验证do | record |
record.validate_photo_quota
end
$ b $ def validate_photo_quota
return self.user $ b $如果self.user.photos(:reload).count> = LIMIT
errors.add(:base,:exceeded_quota)
end
end
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?
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
这篇关于用carrierwave限制文件上传量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!