当多级accepts_nested_attributes_for时,Rails 4强参数

Haw*_*001 7 nested-attributes strong-parameters ruby-on-rails-4

当我尝试保存具有多个accepts_nested_attribetus_for级别的模型时,我遇到了问题.

我的用例是有一个用户页面,用户可以在其中创建多个问题,每个问题也有多个答案.

发生的事情是,由于提交页面上可能存在多个问题,因此在提交时,用户的参数哈希值如下所示:

{"user"=>{"questions_attributes"=>{"0"=>{"desc"=>"question", "answers_attributes"=>{"0"=>{"ans"=>""}}}}}}
Run Code Online (Sandbox Code Playgroud)

因此,我得到的错误是"未经许可的参数:0".如何正确设置强参数权限,以便我可以正确保存所有模型?我可以循环解决问题,并单独保存每一个问题,但这样做有效,但我希望能有更清洁的方法.

user.rb

has_many :questions
accepts_nested_attributes_for :questions
Run Code Online (Sandbox Code Playgroud)

question.rb

belongs_to :user
has_many :answers
accepts_nested_attributes_for :answers
Run Code Online (Sandbox Code Playgroud)

answer.rb

belongs_to :question
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Ann*_*a88 1

尝试这个

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
Run Code Online (Sandbox Code Playgroud)