I am having an issue when I attempt to save a model that has multiple levels of accepts_nested_attribetus_for.
My use case is that there is a user page, where the user can create multiple questions, and also multiple answers per question.
Whats happening is that since there can be multiple questions on the submit page, the parameters hash for the user, on submit, looks like:
{"user"=>{"questions_attributes"=>{"0"=>{"desc"=>"question", "answers_attributes"=>{"0"=>{"ans"=>""}}}}}}
And as such, the error I am getting is "Unpermitted parameter: 0". How would I setup the strong parameters permissions correctly, so that I can save all models correctly? I can cycle through the questions, and save each one individually, and that works, but I was hoping there would be a cleaner way of doing it.
user.rb
has_many :questions
accepts_nested_attributes_for :questions
question.rb
belongs_to :user
has_many :answers
accepts_nested_attributes_for :answers
answer.rb
belongs_to :question
users_controller.rb
def update
user = User.find_by_id params[:id]
user.questions.create question_params(params[:user])
end
def question_params(params)
params.require(:question_attributes).permit(:desc, {:answers_attributes => [:ans]}
end
Try this
def update
user = User.find_by_id params[:id]
user.update(user_params)
end
def user_params
params.require(:user).permit(:desc, :questions_attributes => [:question, answers_attributes => [:ans]])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With