Nested strong parameters in rails - AssociationTypeMismatch MYMODEL expected, got ActionController::Parameters()

Alan H picture Alan H · Jan 31, 2014 · Viewed 9.5k times · Source

I'm rendering a model and it's children Books in JSON like so:

{"id":2,"complete":false,"private":false, "books" [{ "id":2,"name":"Some Book"},.....

I then come to update this model by passing the same JSON back to my controller and I get the following error:

ActiveRecord::AssociationTypeMismatch (Book (#2245089560) expected, got ActionController::Parameters(#2153445460))

In my controller I'm using the following to update:

@project.update_attributes!(project_params)

private

def project_params
    params.permit(:id, { books: [:id] } )
end

No matter which attributes I whitelist in permit I can't seem to save the child model.

Am I missing something obvious?

Update - another example:

Controller:

def create
    @model = Model.new(model_params)
end
def model_params
    params.fetch(:model, {}).permit(:child_model => [:name, :other])
end

Request:

post 'api.address/model', :model => { :child_model => { :name => "some name" } }

Model:

accepts_nested_attributes_for :child_model

Error:

expected ChildModel, got ActionController::Parameters

Tried this method to no avail: http://www.rubyexperiments.com/using-strong-parameters-with-nested-forms/

Answer

Josh Kovach picture Josh Kovach · Feb 2, 2014

Are you using accepts_nested_attributes_for :books on your project model? If so, instead of "books", the key should be "books_attributes".

def project_params
  params.permit(:id, :complete, :false, :private, books_attributes: [:id, :name])
end