jon*_*IVE 15 ruby-on-rails paperclip ruby-on-rails-4
有没有办法阻止验证消息出现两次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 }
Run Code Online (Sandbox Code Playgroud)
这是我的观点:
<% 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 %>
Run Code Online (Sandbox Code Playgroud)
如果我上传无效文件,我会收到以下错误消息:
有没有办法让其中一个出现?我尝试过向模型添加消息:但那么这也只是出现了两次!
谢谢!
Jim*_*eux 24
如果检查@ 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"] }
Run Code Online (Sandbox Code Playgroud)
您需要使用一些Ruby过滤掉其中的一部分.有很多方法可以解决它(请参阅此处了解一些想法),但快速修复可能是删除:photo数组并仅使用来自回形针生成的属性的消息.
@model.errors.delete(:photo)
Run Code Online (Sandbox Code Playgroud)
这应该留给你@model.errors.full_messages这样的:
["Photo content type is invalid", "Photo file size must be less than 1048576 Bytes"]
Run Code Online (Sandbox Code Playgroud)
Hoa*_*Hoa 14
在我看来,下面是一个更好的解决方案
class YourModel < ActiveRecord::Base
...
after_validation :clean_paperclip_errors
def clean_paperclip_errors
errors.delete(:photo)
end
end
Run Code Online (Sandbox Code Playgroud)
见@rubiety评论点击这里
| 归档时间: |
|
| 查看次数: |
3991 次 |
| 最近记录: |