form_for error messages in Ruby on Rails

前端 未结 4 864
离开以前
离开以前 2020-12-10 12:28

What is the preferred way to display validation error messages using form_for in Rails 4?

<%= form_for @post do |f| %>
  ...
<% end %&g         


        
相关标签:
4条回答
  • 2020-12-10 13:01

    This is how I am displaying them for my form object called @location:

    <% if @location.errors.any? %>
    <ul>
      <% @location.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
    <% end %>
    

    Note: put the above code after the <%= form_for @location do |f| %> line

    0 讨论(0)
  • 2020-12-10 13:03

    I know this isn't exactly what was asked, but if you are using the simple_form gem, which I recommend, you can use f.error_notification which takes :message as an option.

    = f.error_notification message: form_errors_for(your_object)
    

    I use a method pretty similar to Wes's answer; form_errors_for inside application_helper.rb

    def form_errors_for_base(object)
      if object.errors.messages[:base].present?
        object.errors.messages[:base].join(",\n") + "."
      else
        nil
      end
    end
    
    0 讨论(0)
  • 2020-12-10 13:05

    My preferred way of doing this and keeping the code simple and DRY, is the following:

    Create a new helper inside of application_helper.rb

    # Displays object errors
    def form_errors_for(object=nil)
      render('shared/form_errors', object: object) unless object.blank?
    end
    

    Create a new shared partial in shared/_form_errors.html.erb

    <% content_for :form_errors do %>
      <p>
        <%= pluralize(object.errors.count, "error") %> prevented the form from being saved:
      </p>
    
      <ul>
        <% object.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    <% end %>
    

    Edit your application.html.erb file to include the errors where you want them:

    <%= yield :form_errors %>
    

    Finally, place the helper at the start of each form:

    <%= form_for(@model) do |f| %>
      <%= form_errors_for @model %>
    
      <%# ... form fields ... %>
    <% end %>
    

    This makes it extremely simple to manage and show your form errors across many forms.

    0 讨论(0)
  • 2020-12-10 13:08

    Same as Rails 3 -- see f.error_messages in Rails 3.0 or http://railscasts.com/episodes/211-validations-in-rails-3 for many different possibilities.

    My personal preference is to use simple_form and have it put the error next to the input.

    0 讨论(0)
提交回复
热议问题