Ruby on Rails 4 - 重复的回形针验证消息 [英] Ruby on Rails 4 - Duplicate paperclip validation messages

查看:42
本文介绍了Ruby on Rails 4 - 重复的回形针验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的模型:

has_attached_file :photo, :styles =>{ :thumb =>"215x165" }, :default_url =>"/images/:style/missing.png"validates_attachment :photo, :presence =>真的,:content_type =>{:content_type =>"图像/jpg" },:尺寸 =>{ :in =>0..0.5.兆字节}

这是我的观点:

<% if @product.errors.any?%><p>发现以下错误:</p><ul><% @product.errors.full_messages.each 做 |message|%><li>-<%=消息%></li><%结束%><%结束%>

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

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

有没有办法让其中一个出现?我曾尝试将 message: 添加到模型中.但是这也只是出现了两次!

谢谢!

解决方案

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

>

{:photo_content_type=>["无效"],:photo=>["无效", "必须小于 1048576 字节"],:photo_file_size=>["必须小于 1048576 字节"] }

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

@model.errors.delete(:photo)

这应该给你一个 @model.errors.full_messages 像这样:

["图片内容类型无效", "图片文件大小必须小于 1048576 字节"]

Is there any way to prevent validation messages appearing twice for Paperclip upload validations?

Here is my model:

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 }

Here is my view:

<% 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 %>

If I upload an invalid file I get the following error messages:

  • Photo content type is invalid
  • Photo is invalid

Is there any way to make just one of these show up? I have tried adding message: to the model. But then this just comes up twice too!

Thank you!

解决方案

If you inspect the @model.errors hash, you can see it returns an array for the :photo attribute, and a message for each paperclip validator.

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

You'll need to filter one lot of them with a bit of Ruby. There are many ways to go about it (see here for some ideas), but a quick fix could be to delete the :photo array and use just the messages from paperclip generated attributes.

@model.errors.delete(:photo)

This should leave you with a @model.errors.full_messages like this:

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

这篇关于Ruby on Rails 4 - 重复的回形针验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆