2016-06-13 48 views
0

我想添加'请注意,您必须再次选择所有图像和相关车辆。到任何验证错误结束时,不管有多少错误,因此例如将此文本添加到每条错误消息的末尾不是一个选项,因为如果存在多个错误,它将显示多次。将某些文本添加到任何验证错误消息的末尾

有什么办法可以将特定的文本添加到验证错误消息的末尾吗?

尝试谷歌,但没有发现任何东西。

+1

您可以将它添加到您在视图中显示错误的位置。这就是说我认为适当的解决方案是不要求用户重新选择图像和相关车辆,但这只是一个假设。 –

+0

当然,但现在必须离开它,因为有更重要的事情要处理。明天将尝试你的解决方案,但觉得应该有更好的方式,而不是把它放在视图中。 –

回答

1

这很容易实现,但是根据您列出的验证数量而定,这可能非常乏味。我将给出一些例子,以便您可以决定什么是最适合您的需求:

如果使用Rails的内置验证(例如prescence,uniqueness等),您可以在验证中添加自己的消息以及标准输出或用自己的完全替代它:

validates :username, :email, :title, :another_attribute,:omg_another_attribute, :password, presence: { :message => "cant be blank. Notice that you have to select all the images and related vehicles again for not filling out the form ya dumbo!"} 

这将列出每个字段的错误消息,他们留下的空白。如果您想在所有错误消息的末尾添加错误以提醒他们这个问题,您可以进行自定义验证,检查是否存在其他错误,然后在末尾添加一次自己的错误,如:

#Make sure to put this custom validate method after all the other validators since they are run in order from top to bottom and you want to see if the others have failed 
validate :add_blanket_error_when_one_or_more_errors_happen 

def add_blanket_error_when_one_or_more_errors_happen 
    if self.errors.count > 0 then self.errors.add(:base, "Notice you were being dumb again and now have to fill more stuff out.") end 
end 

我通常会将这样的一般错误添加到“基本”字段,但如果您不想添加额外的样式/标记,则可以将其附加到表单中的任何字段。在你看来,如果你选择了将其添加到“基地”字段您可以直接在表格上把这个消息如果存在这样做:

 <% unless @the_form_object_youre_using_here.errors[:base].blank? %> 
     <div> 
      <span class="error-explanation"><%= @again_the_form_object_here.errors[:base].first %></span> 
     </div> 
     <% end %> 

这也将让你的风格跨度等。

不幸的是,您可以添加到您的模型中没有简单的单线程来追加一个毯子消息到所有失败的验证。甚至尝试看似无害的东西,像一个自定义验证,以实现它(不要试试这个,除非你有你的任务管理器准备,因为它会导致内存泄漏,甚至让你的电脑崩溃,如果你不杀死的过程很快)

**DONT DO IT IF YOU ENJOY COORS LIGHT OR PREFER LONG WALKS ON THE BEACH** 

    validate :append_messages_to_all_failed_validations 

    def append_messages_to_all_failed_validations 
    self.errors.each do |attribute, error| 
     #**YOU SHOULDNT BE DOING THIS LOL** 
     self.errors[attribute.to_sym] = "#{error} plus some" 
    end 
    end