ActiveModel form using fields_for in Rails 5


I have an ActiveModel “form object” which “has many” patients (another ActiveModel “form object”). The idea being the user can fill in the form and add as many patients.

- @form.patients.each do |patient|
  = form.fields_for 'patients[]', patient do |patient_form|

This worked fine in Rails 4 and as far as I remember inputs where named something like patients[][name].

This was an Array in params such as { patients: [ {name: 'foo'} ] }.

However it seems this may have changed with Rails 5, looking at the source it seems if name ends in [] and there is no index given it will try and insert an id.

Giving an input name such as patients[1][name].

However the form object (ActiveModel) has no #id method and I get an NoMethodError. And even if it did this would give a params has which would be a Hash such as { patients: { '1' => { name: 'foo' } } }.

If I just do form.fields_for 'patients', patient all input have the same name and thus overwrite each other in params.

One solution is to add a “fake” #id method to the “form object”:

# form object (ActiveModel)
def id

and then convert the params hash ({ id => attributes }) to an array of attributes ([attributes]):


While I don’t mind ‘fixing’ the params too much adding a useless #id method to the form seems too much.