Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Strong Parameters when multiple-level accepts_nested_attributes_for

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
like image 512
Hawkeye001 Avatar asked Aug 29 '15 15:08

Hawkeye001


1 Answers

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
like image 76
Anna88 Avatar answered Oct 06 '22 13:10

Anna88