【问题标题】:Ruby on Rails 4 - Duplicate paperclip validation messagesRuby on Rails 4 - 重复的回形针验证消息
【发布时间】:2013-11-12 15:46:06
【问题描述】:

有什么方法可以防止回形针上传验证的验证消息出现两次?

这是我的模型:

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: 添加到模型中。但是这也只是出现了两次!

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 paperclip


    【解决方案1】:

    如果您检查 @model.errors 哈希,您可以看到它为 :photo 属性返回一个数组,并为每个回形针验证器返回一条消息。

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

    您需要使用一些 Ruby 过滤其中的很多。有很多方法可以解决这个问题(请参阅here 了解一些想法),但快速修复可能是删除 :photo 数组并仅使用来自回形针生成的属性的消息。

    @model.errors.delete(:photo)
    

    这应该会给您留下这样的@model.errors.full_messages

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

    【讨论】:

    • @Jimeux,你的回答在当前情况下是正确的,但是我已经为这个问题的实际解决方案打开了一个 PR。如果您希望将此解决方案合并到回形针 github.com/thoughtbot/paperclip/pull/1418 中,请支持该问题
    【解决方案2】:

    在我看来,下面是一个更好的解决方案

    class YourModel < ActiveRecord::Base
      ...
    
      after_validation :clean_paperclip_errors
    
      def clean_paperclip_errors
        errors.delete(:photo)
      end
    end
    

    查看@rubiety here的评论

    【讨论】:

    • 谢谢你救了我!
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2015-06-26
      • 1970-01-01
      • 2013-04-15
      • 2016-11-08
      • 2022-01-26
      相关资源
      最近更新 更多