Published by Dan Cunning on May 18, 2015

f.label and errors.full_messages

Why you should never use the explicit “content” parameter of label_tag or the form builder’s label method.

Filed under Troubleshooting

Common Mistake

Can you spot the bug?

<%= form_for @post do |f| %>
  <%= @post.errors.full_messages.join(', ') %>

  <p>
    <%= f.label :user_name, 'Author' %>
    <%= f.text_field :user_name %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

full_messages will display "User name can't be blank" while the text field is labeled "Author" which will likely cause confusion.

Proper Implementation

While the FormBuilder's label method accepts content_or_options, I consider "content" deprecated due to error message display and localization concerns. Here's the proper implementation:

activerecord:
  attributes:
    post:
      user_name: Author
<%= form_for @post do |f| %>
  <%= @post.errors.full_messages.join(', ') %>

  <p>
    <%= f.label :user_name %>
    <%= f.text_field :user_name %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

With that change you're properly set up for new language support and the field names in the error messages will match your labels.