问题:如何限制使用Paperclip为“图片”类(接受图像)上载的图像数量?
我有一个模型,其中项目与图片具有一对多的关系,并且图片具有附加的文件图像,如以下代码所示:
class Picture < ActiveRecord::Base
belongs_to :item
has_attached_file :images, styles: { large: "600x600>", medium: "300x300>", thumb: "100x100>" },
validates_attachment_content_type :images, :content_type => /^image\/(jpg|jpeg|pjpeg|png|x-png|gif)$/, :message => 'file type is not allowed (only jpeg/png/gif images)'
end
这是Item类:
class Item < ActiveRecord::Base
has_many :pictures, :dependent => :destroy
end
关于上传的所有内容都可以完美运行。但是,我该怎么做才能将图片模型修改为最多仅接受4张上传的图片?另外,是否可以弹出窗口说“您最多只能上传四个图像”?
您还需要我提供什么其他信息? (架构/控制器?考虑到太大,我不太喜欢上传这些文件)
答案 0 :(得分:0)
您可以在Item
模型中添加自定义验证方法(这样每个项目最多可以包含4张图片)
https://guides.rubyonrails.org/active_record_validations.html#custom-methods
class Item < ActiveRecord::Base
validate :only_4_pictures
def only_4_pictures
errors.add(:pictures, "You can't upload more than 4 pictures") if pictures.length > 4
end
end
这将防止对象被保存。
然后如何显示弹出窗口确实取决于视图的代码,您可以使用object.errors [:pictures]访问对象和错误。