f.error_messages in Rails 3.0

Viewed 36609

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. I am following the getting started guide, which uses the deprecated method when implementing the comments form. For example:

<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <%= f.error_messages %>
<div class="field">
  <% f.label :commenter  %><br />
  <%= f.text_field :commenter  %>
</div>
<div class="field">
  <%= f.label :body %><br />
  <%= f.text_area :body %>
</div>
<div class="actions">
  <%= f.submit %>
</div>
<% end %>

Here is the correct way to do it (as generated by the scaffold):

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
 . . . 

I understand that I use the @post variable in the latter example, but what variable do I reference in the former to get the error messages for comment creation?

7 Answers

a rather simple implementation can be achieved with

class ActionView::Helpers::FormBuilder
  def error_message(method)
    return unless object.respond_to?(:errors) && object.errors.any?

    @template.content_tag(:div, object.errors.full_messages_for(:"#{method}").first, class: 'error')
  end
end

which allows one to use

 <%= form.label :first_name %>
 <%= form.text_field :first_name %>
 <%= form.error_message :first_name %>

and with the following sass

@import variables

.error
  padding: $margin-s
  margin-left: $size-xl
  color: red

.field_with_errors
  input
    border: 1px red solid

  input:focus
    outline-color: red

it looks like

enter image description here


using simple form gives you quite similiar functionality with more advanced functionality.

For example check out their examples with bootstrap

Related