f.error_messages in Rails 3.0

前端 未结 6 1013
难免孤独
难免孤独 2020-11-29 00:04

Rails 3.0 deprecated f.error_messages and now requires a plugin to work correctly - I however want to learn how to display error messages the (new) native way.

6条回答
  •  [愿得一人]
    2020-11-29 00:13

    The best and clean way to implement error_messages in your form is by implementing error_messages in a FormBuilder.

    For example, here is the error_messages method I've implemented for my last project. By implemeting your own FormBuilder you can follow the rules and styles of your webdesigner... Here is an example that will output the errors list in ul/li's with some custom styles :

    class StandardBuilder < ActionView::Helpers::FormBuilder
      def error_messages
        return unless object.respond_to?(:errors) && object.errors.any?
    
        errors_list = ""
        errors_list << @template.content_tag(:span, "There are errors!", :class => "title-error")
        errors_list << object.errors.full_messages.map { |message| @template.content_tag(:li, message) }.join("\n")
    
        @template.content_tag(:ul, errors_list.html_safe, :class => "error-recap round-border")
      end
    end
    

    Then in my forms :

    = f.error_messages
    

    And that's all.

提交回复
热议问题