1

I am trying to add field errors in rails with field_error_proc. But I could not find a way to add the error with the field name. Below is the code that I am using to generate a field with errors in rails.

ActionView::Base.field_error_proc = proc do |html_tag, instance|
  if html_tag =~ /^<label/
    %(#{html_tag}).html_safe
  else
    %(#{html_tag}<div class="help-block"><ul role="alert"><li>#{instance.error_message.first}</li></ul></div>).html_safe
  end
end

below is the output of the above code. What I want is to have an error with field name like "Email is required" so as to have the common pattern for error(same as FE validation error)

Error generated with field error proc for presence validation

This is the output of the FE validation.

enter image description here

Aarthi
  • 1,451
  • 15
  • 39

1 Answers1

1

If you display the content of your instance block argument you should see something like this:

#<ActionView::Helpers::Tags::TextField:0x00007f54102118d8 @method_name="email", @object_name="user" # ...(more)

So in order to get the method name of the validated input you could use:

ActionView::Base.field_error_proc = proc do |html_tag, instance|
  method_name = instance.instance_variable_get("@method_name").humanize
  if html_tag =~ /^<label/
    %(#{html_tag}).html_safe
  else
    %(#{html_tag}<div class="help-block"><ul role="alert"><li>#{method_name} #{instance.error_message.first}</li></ul></div>).html_safe
  end
end
Manoel M. Neto
  • 616
  • 4
  • 5