Abid
Abid

Reputation: 7227

Rails form inline errors

I have a large form with a lot of fields, The way we get back errors in rails is that the they reside inside the model object. i want a clean way to show errors besides each field instead of showing the separately. Is there a gem that can do this and if now what can be the best way to do it.

I want each error to show besides the field the error is on.

Upvotes: 0

Views: 1775

Answers (2)

pduey
pduey

Reputation: 3786

Assuming you are using Rails 3+ and the Rails Form Helpers, you do not need any gems and you do not need to iterate over the errors collection.

Well, that's not entirely true, but Rails does it for you. You just need to provide a proc.

I add the following to .../config/application.rb:

# wrap each form field that has an error with the following. 
# note, condition for arrays and singletons.
config.action_view.field_error_proc = Proc.new do |html_tag, instance|
  if instance.error_message.kind_of?(Array)
    %(<span class="validation-error">#{html_tag}</span>).html_safe
  else
    %(#{html_tag}<span class="validation-error">&nbsp;</span>).html_safe
  end
end

Make sure to define the CSS class validation-error. That should get it working, then you can tweak it to fit your needs. Note, your CSS can be specific to each field type, e.g., input, textarea, select, etc.

And of course restart the Rails app.

I actually learned this in another thread on SO, but I can't find it now so I can't provide the reference.

Upvotes: 5

Jeff Dickey
Jeff Dickey

Reputation: 5034

Try simple_form or formtastic to make this easier. With those, it'll automatically do what you're looking for.

If you want to make your views really long, or just don't want to use a gem, you can also do this:

<span class="help-inline"><%= @object.errors[:field] %></span>

But that'll get icky fast.

Upvotes: 3

Related Questions