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

Dip*_*hal 6 ruby-on-rails ruby-on-rails-5

params.require(:task).permit(:summary, comments_attributes: [:id, :content])
Run Code Online (Sandbox Code Playgroud)

我想在comments_attributes中添加user_idproject_id

user_id    = current_user.id
project_id = project.id
Run Code Online (Sandbox Code Playgroud)

我尝试了下面但没有工作

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

请帮助我我该怎么做?

ush*_*sha 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])
Run Code Online (Sandbox Code Playgroud)

  • 这在 Rails 5 中是如何工作的?看来 `deep_merge` 不再是 `ActionController::Parameters` 的子类。我在 Rails 5 中收到“deep_merge”的“未定义方法”错误。 (3认同)