在 Rails 中自定义表单错误消息

Customize Form Error Messages in Rails

所以,我正在尝试想出一种方法来自定义 form_for 中的错误消息。在我看来,最优雅的方法是 文本区域本身中。到目前为止,我尝试过的任何方法都会完全弄乱表格。请分享您的想法和方法。 简单形式:

 <%= f.label :name, 'Name' %><br> 
 <%= f.text_field :name, size: 30 %>

 <%= f.label :password, 'Password' %><br>
 <%= f.password_field :password, size: 30 %>

<%= f.label :password_confirmation, 'Confirm' %><br>
<%= f.password_field :password_confirmation, size: 30 %>

<%= f.submit %>

如您所见,这里没有提到任何错误,因为我添加了如下初始化程序:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
errors = Array(instance.error_message).join(',')

if html_tag =~ /^<label/
    html_tag
    else
    %(#{html_tag}<span class="validation-error">&nbsp;#{errors}</span>).html_safe
end
end

使用辅助方法

def errors_for(model, attribute)
  if model.errors[attribute].present?
    content_tag :span, :class => 'error_explanation' do
      model.errors[attribute].join(", ")
    end
  end
end

并且在视图中:

  <%= lesson_form.text_field :description %><br />
  <%= errors_for @lesson, :description %>    

显示错误消息的另一种方式:

    def error_messages_for object
      error_content = ''
      if object.errors.any?
       error_content += content_tag(:div, :id => 'error_explanation',  :class => 'alert alert-error') do
        content_tag(:h3, "#{pluralize(object.errors.count, "error")} prohibited this #{object.class.name.downcase} from being saved:") +
        content_tag(:ul, class: 'unstyled') do
          object.errors.full_messages.each do |message|
            concat content_tag(:li, "#{message}") if message.present?
          end
        end
      end
    end
    error_content.html_safe
  end
    Inside views use this helper:
    <%= error_messages_for @sample %>

更好的方法是使用full_messages_for:

在你的助手中定义:

def error_message_for(record, field)
  record.full_messages_for(field).join(",")
end  

如果您不想显示完整消息,您可以使用:

  record.errors.get(field).join(",")

然后在您看来:

<%= errors_message_for @lesson, :description %>

我的通用解决方案版本:

辅助方法:

def errors_for(model, attribute)
  if model.errors[attribute].any?
    content_tag :span, class: 'error' do
      attribute.to_s.humanize + " " + model.errors[attribute].to_sentence
    end
  end
end

观点:

<%= errors_for @user, :name %>

你得到什么:

"Name can't be blank and is too short (minimum is 2 characters)"