Ruby on Rails 4 - Paperclip 验证消息重复

16

有没有办法防止Paperclip上传验证出现两次?

这是我的模型:

has_attached_file :photo, :styles => { :thumb => "215x165" }, :default_url => "/images/:style/missing.png"

validates_attachment :photo, :presence => true,
:content_type => { :content_type => "image/jpg" },
:size => { :in => 0..0.5.megabytes }

这是我的观点:

<% if @product.errors.any? %>
<p>The following errors were found:</p>
  <ul>
    <% @product.errors.full_messages.each do |message| %>
      <li>- <%= message %></li>
    <% end %>
  </ul>
<% end %>

如果我上传一个无效的文件,我会收到以下错误消息:

  • 照片内容类型无效
  • 照片无效

有没有办法只显示其中一个?我已经尝试将message:添加到模型中。但是这样也会出现两次!

谢谢!

3个回答

25
如果您检查@model.errors哈希表,您可以看到它返回一个数组来表示:photo属性,而每个Paperclip验证器都有一条消息。

如果您检查@model.errors哈希表,您可以看到它返回一个数组来表示:photo属性,而每个Paperclip验证器都有一条消息。

{:photo_content_type=>["is invalid"], 
 :photo=>["is invalid", "must be less than 1048576 Bytes"], 
 :photo_file_size=>["must be less than 1048576 Bytes"] }

你需要用一些 Ruby 过滤掉其中的一个。有许多方法可以实现(请参见此处获取一些想法),但快速修复可能是删除 :photo 数组并仅使用由 Paperclip 生成的属性中的信息。

@model.errors.delete(:photo)

这应该让你得到一个像这样的@model.errors.full_messages

["Photo content type is invalid", "Photo file size must be less than 1048576 Bytes"]

@Jimeux,你的回答在当前情况下是正确的,但我已经为解决这个问题的实际方案打开了一个PR。如果你想将此解决方案合并到Paperclip中,请为该问题点赞。 https://github.com/thoughtbot/paperclip/pull/1418 - Kashif Umair Liaqat

15

我个人认为,以下解决方案更好。

class YourModel < ActiveRecord::Base
  ...

  after_validation :clean_paperclip_errors

  def clean_paperclip_errors
    errors.delete(:photo)
  end
end

参见@rubiety在此处的评论


谢谢你,你救了我! - Afsanefda

3
请注意,之前答案中的解决方案在您不需要存在验证时效果很好。这是因为@model.errors.delete(:photo)会删除重复项以及存在验证错误。下面的代码保留了指定为retain_specified_errors方法参数的属性的验证错误。
class YourModel < ActiveRecord::Base
  ...

  after_validation {
    retain_specified_errors(%i(attr another_att))
  }

  def retain_specified_errors(attrs_to_retain)
    errors.each do |attr|
      unless attrs_to_retain.include?(attr)
        errors.delete(attr)
      end
    end
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接