Reputation: 27852
I am trying to add some errors to a form close to the field that caused the error and here is how I am doing this:
<%= 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 an non repetitive way of doing this. As you see I am repeating the same unless errors... for each of the fields.
Upvotes: 3
Views: 3359
Reputation: 65467
Use a 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 view:
<%= 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 could use simple_form which will do it all for you like this:
<%= simple_form_for @lesson do |f| %>
<%= f.input :description %>
<%= f.input :category %>
<%= f.button :submit %>
<% end %>
And if you use simple_form and haml, things look a bit neater:
= simple_form_for @lesson do |f|
= f.input :description
= f.input :category
= f.button :submit
The above will show the error next to the field and will detect type of the attribute and show the appropriate input box (eg text, password, checkbox etc.), all with one simple line f.input
.
Upvotes: 12