form_for error messages in Ruby on Rails form_for error messages in Ruby on Rails ruby ruby

form_for error messages in Ruby on Rails


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


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 errorsdef 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.


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.