如何将变量放在ruby on rails上的验证自定义错误消息中

时间:2014-03-16 15:06:39

标签: ruby-on-rails ruby

我想在自定义错误消息中放置一个object属性,如:

validates_attachment :picture, 
:content_type => { :content_type => ["image/jpg", "image/gif", "image/png", "image/jpeg"], message: "File type is invalid: #{object.file_name}" }

怎么做?

3 个答案:

答案 0 :(得分:1)

您只能在给定模型中的attribute方法的message选项中访问validates(经过验证)及其值。

这是一个解决方法:

validates_attachment :picture, 
:content_type => { :content_type => ["image/jpg", "image/gif", "image/png", "image/jpeg"], message: "File type is invalid:" } ## Remove #{object.file_name}

在视图中,您将显示验证错误消息:

  <% model_instance.errors.full_messages.each do |msg| %>
    <% if msg == "Picture File type is invalid:" %>  ## full_messages prepends attribute name to message
      <p><%= msg + "#{model_instance.picture_file_name}" %></p>
    <% else %>
      <p><%= msg %></p>
     <% end %>
  <% end %> 

注意:model_instance替换为视图中传递的模型实例。

答案 1 :(得分:0)

使用%{value}代替#{object.file_name}

validates_attachment :picture, 
:content_type => { :content_type => ["image/jpg", "image/gif", "image/png", "image/jpeg"], message: "File type is invalid: %{value}" }

答案 2 :(得分:0)

我花了两天时间,但设法找到了一个非常干净的方法,可以将所有代码保存在模型本身的简单方法中,这是我们希望在不担心视图的情况下进行验证的地方。

  1. 允许正常创建验证消息,您无需尝试在验证助手中进行更改。

  2. 创建一个after_validation回调,该回调将在到达视图之前在后端替换该验证消息。

  3. after_validation方法中,您可以使用动态值并将其插入到验证消息中。


#this could be any validation
validates_attachment :picture, :content_type => { :content_type => ["image/jpg", "image/gif", "image/png", "image/jpeg"], message: "Add anything you want here we will replace it anyway" }

after_validation :replace_validation_message

def replace_validation_message
    custom_value = #any value you would like
    errors.messages[:name_of_the_attribute] = ["This is the replacement message where 
    you can now add your own dynamic values!!! #{custom_value}"]
end

after_validation方法的作用域将比内置的rails验证帮助器大得多,因此您可以像使用object.file_name一样访问要验证的对象。在您试图调用它的验证帮助器中,这不起作用。