1

我有一个用户模型和一个带有载波的图像模型。

我想限制用户可以上传的图片数量,因为我有第二种形式,用户可以在其中上传图片,我希望他只能上传 3 张图片。有没有一个优雅的解决方案?还是我必须制作一个自定义验证器来计算用户的图像数量?

4

1 回答 1

6

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
于 2013-01-09T15:15:53.973 回答