Rails: errors close to specific fields in forms

I am trying to add some errors to a form close to the field that caused the error, and here is how I do it:

 <%= lesson_form.text_field :description %><br />
  <% unless @lesson.errors[:description].blank? %>
    <span id="error_explanation">
      Description <%= @lesson.errors[:description].join(", ") %>
    </span>
  <% end -%>

  <%= lesson_form.label :category %>
  <%= lesson_form.text_field :category %><br />
  <% unless @lesson.errors[:category].blank? %>
    <span id="error_explanation">
      Category <%= @lesson.errors[:category].join(", ") %>
    </span>
  <% end -%>

I would like to know if there is a better way of repeating. As you can see, I repeat the same if there are errors ... for each of the fields.

+3
source share
1 answer

Use the helper method:

def errors_for(model, attribute)
  if model.errors[attribute].present?
    content_tag :span, :class => 'error_explanation' do
      model.errors[attribute].join(", ")
    end
  end
end

And in sight:

<%= lesson_form.text_field :description %><br />
  <%= errors_for @lesson, :description %>

  <%= lesson_form.label :category %>
  <%= lesson_form.text_field :category %><br />
  <%= errors_for @lesson, :category %>
<% end %>

Or you can use simple_form , which will do all this for you as follows:

<%= simple_form_for @lesson do |f| %>
  <%= f.input :description %>
  <%= f.input :category %>
  <%= f.button :submit %>
<% end %>

And if you use simple_form and haml , everything looks a bit neat:

= simple_form_for @lesson do |f|
  = f.input :description
  = f.input :category
  = f.button :submit

(, , , ..), f.input.

+11

All Articles