Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing fields with errors for nested forms in Rails 3.2 + SimpleForm

I have a Flight model nested inside a FlightLog model. A FlightLog may contain many flights.

I'm using SimpleForm with the bootstrap installation, which makes it possible to surround form elements with errors with the error class when a validation fails.

The problem is, that even though validations are triggered for the nested model, the fields with errors inside the simple_fields_for are not being marked, so it's not possible to determine which attribute is not valid.

After examining the errors hash when calling the create action, I can see that it is correctly populated with the errors at the top level, and the errors of the nested resources inside each resource.

How could I modify the behavior of simple_form to add the errors class to the control group of each nested model to match the behavior of the parent?

Thanks in advance.

enter image description here

like image 678
bruno077 Avatar asked Apr 02 '12 14:04

bruno077


2 Answers

If you are using simple_form with bootstrap, this does work - you just need to set up a few items correctly:

1 - Use the simple_form bootstrap wrappers (from simple_form 2.0) - you can find them in the github repo under config/initializers/simple_form.rb (https://github.com/rafaelfranca/simple_form-bootstrap)

2 - For nested forms to display the errors, you must be sure you provide an object. f.simple_fields_for :nested_model won't work, you need to use f.simple_fields_for parent_model.nested_model or f.simple_fields_for :nested_model, parent_model.nested_model so that the form can get the necessary object.

If you still don't get anything, verify that the form is really getting the object you think it is, with errors, by outputting the errors data on your nested object: parent_model.nested_model.errors.full_messages.to_sentence

like image 84
Hollownest Avatar answered Nov 09 '22 05:11

Hollownest


I have been using custom accessors instead of the _id fields, so that's why they weren't getting notified when they had errors. I finally resolved to use f.error :attr_name under each accessor and changing the styling manually with JS

like image 2
bruno077 Avatar answered Nov 09 '22 05:11

bruno077