Search code examples
ruby-on-railsnested-formsnested-attributesaccepts-nested-attributes

Rails5, nested form, undefined param


Huston, we have a problem:

class FirstModel 
 has_many :merged_models
 has_many :second_models, :through => :merged_models
end

class SecondModel 
 has_many :merged_models
 has_many :first_models, :through => :merged_models
end

class MergedModel 
 belongs_to :first_model
 belongs_to :second_model
end

Form:

<%= form_for(first_model) do |f| %>
 <%= f.fields_for :merged_model do |ff| %>
    <%= ff.label :date %>
    <%= ff.date_select :start_date %>

Problem:

Processing by FirstModelsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"f+D8AaVzM6ahrUyo/nwxISFEleVrXGxo8m30sIiLIe7gvG8J9KfONjuT09j6z3M4Rvw+n3Hm6PMddOtfbgjt5g==", "first_model"=>{"first_name"=>"yyyy", "last_name"=>"yyy", "merged_model"=>{"start_date(1i)"=>"2017", "start_date(2i)"=>"2", "start_date(3i)"=>"28", "second_model_id"=>"1"}}, "commit"=>"Create"} Unpermitted parameter: merged_model Unpermitted parameter: merged_model

First model's controller's strong params:

  params.require(:first_model).permit(:first_name, :last_name, merged_models_attributes: [:id, :start_date])

First model acccepts nested attributes of merged model:

  accepts_nested_attributes_for :merged_models

However, after creating a FirstModel, MergedModel does not get created. Tried to create it in form:

  <%= f.fields_for :merged_model [first_model.merged_models.build] do |ff| %>

But got:

no implicit conversion of MergedModel into Integer

Not completely understand what that means..

Also tried creating a new MergedModel from a FirstModel's create action, with a bang:

@merge_model = MergedModel.create!

And got the same error - no implicit conversion...

Could anyone explain more about this? I feel its about passing an Array of my MergedModel's params into MergedModel's params...? I am totally lost here...


Solution

  • Your form should have fields_for :merged_models instead of just merged_model.