加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby on Rails 4 – 重复的回形针验证消息

发布时间:2020-12-16 20:04:50 所属栏目:百科 来源:网络整理
导读:有没有办法阻止验证消息出现两次Paperclip上传验证? 这是我的模特儿: has_attached_file :photo,:styles = { :thumb = "215x165" },:default_url = "/images/:style/missing.png"validates_attachment :photo,:presence = true,:content_type = { :content
有没有办法阻止验证消息出现两次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 %>

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

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

有没有办法让其中一个出现?我已经尝试添加消息:到模型.但是,这也刚刚出现了两次!

谢谢!

解决方法

如果您检查@ 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的一些想法),但一个快速的修复可能是删除:照片数组,只使用回形针生成的属性的消息.

@model.errors.delete(:photo)

这应该让你有一个@ model.errors.full_messages,如下所示:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读