如何在permit + Rails中合并嵌套属性

时间:2016-12-05 18:47:09

标签: ruby-on-rails ruby-on-rails-5

params.require(:task).permit(:summary, comments_attributes: [:id, :content])

我想在comments_attributes中添加 user_id project_id

user_id    = current_user.id
project_id = project.id

我试过以下但没有工作

params.require(:task).permit(:summary, comments_attributes: [:id, :content]).merge(user_id: current_user.id, comments_attributes: [user_id: current_user.id, project_id: project.id])

请帮帮我怎么做?

4 个答案:

答案 0 :(得分:1)

您必须使用deep_merge

params.require(:task).permit(:summary, comments_attributes: [:id, :content]).deep_merge(user_id: current_user.id, comments_attributes: [user_id: current_user.id, project_id: project.id])

答案 1 :(得分:1)

尽管是一个老问题,正确的答案恕我直言是这个->

在Rails 5中,您应该使用reverse_merge

而不是.to_h.deep_merge
params.require(:task).permit(:summary, comments_attributes: [:id, :content]).reverse_merge(user_id: current_user.id, comments_attributes: [user_id: current_user.id, project_id: project.id])

答案 2 :(得分:0)

首先将允许的参数转换为散列,然后将散列深度合并:

"scripts": {
 "postinstall": "pip install pandas"
}

答案 3 :(得分:0)

 params[:task][:comments_attributes].merge!({user_id: current_user.id, project_id: project.id})