No implicit conversion of type Array to Integer with Rails 4.0.2 and Strong Parameters

喜你入骨 提交于 2019-12-13 04:26:16

问题


I'm trying to update a nested model with a simple has_many / belongs_to association

I've setup parameters in the controller with

params.require(:survey).permit(:name, :questions[[:id, :content]])

but I get the No implicit conversion of type Array to Integer

console dump below. From similar issues I've read the problem may be how this :questions_attributes is hashed - no idea where this needs to be fixed tho - any ideas appreciated!

Thanks

Started PATCH "/surveys/1" for 127.0.0.1 at 2014-01-04 15:53:31 +1100
Processing by SurveysController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"l5ANLS/y2Z+aB4xiJzEw+pF+j7V7LQk4THfU7mkTGX4=", "survey"=>{"name"=>"do u like cats?", "questions_attributes"=>{"0"=>{"content"=>"nope3", "id"=>"1"}, "1"=>{"content"=>"no way", "id"=>"2"}}}, "commit"=>"Update Survey", "id"=>"1"}
  Survey Load (0.3ms)  SELECT "surveys".* FROM "surveys" WHERE "surveys"."id" = $1 LIMIT 1  [["id", "1"]]
Completed 500 Internal Server Error in 2ms

TypeError (no implicit conversion of Array into Integer):
  app/controllers/surveys_controller.rb:72:in `[]'
  app/controllers/surveys_controller.rb:72:in `survey_params'
  app/controllers/surveys_controller.rb:44:in `block in update'
  app/controllers/surveys_controller.rb:43:in `update'

Update: This is what is posted when :question_attributes does not have extra parentheses

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"l5ANLS/y2Z+aB4xiJzEw+pF+j7V7LQk4THfU7mkTGX4=",
 "survey"=>{"name"=>"do u like cats?",
 "questions_attributes"=>{"0"=>{"content"=>"nope2",
 "id"=>"1"},
 "1"=>{"content"=>"no way",
 "id"=>"2"}}},
 "commit"=>"Update Survey",
 "id"=>"1"}

回答1:


just replace :questions[[:id, :content]] with

:questions_attributes => [:id, :content]



回答2:


Your params permit statement is not quite right.

Assuming you're using accepts_nested_attributes_for in your model and fields_for in your form, you'll need to update your permit statement as follows:

params.require(:survey).permit(:name, questions_attributes: [:id, :content])

If you want to be able to delete child objects through the form too, you'll need to add :_destroy into the questions_attributes array too.



来源:https://stackoverflow.com/questions/20917161/no-implicit-conversion-of-type-array-to-integer-with-rails-4-0-2-and-strong-para

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!