ruby-on-rails 如何在permit + Rails中合并嵌套属性

xvw2m8pv  于 2023-02-26  发布在  Ruby
关注(0)|答案(5)|浏览(194)
params.require(:task).permit(:summary, comments_attributes: [:id, :content])

我想在注解属性中添加用户ID项目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])

请帮帮我我怎么能这样做?

23c0lvtd

23c0lvtd1#

虽然是一个老问题,正确的答案IMHO是这样的-〉
在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])
mrzz3bfm

mrzz3bfm2#

你必须使用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])
nxagd54h

nxagd54h3#

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

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

7d7tgy0s4#

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

35g0bw715#

我无法使current top answer工作。reverse_merge本身似乎不会迭代地将reverse_merge向下调用到ActionController::Parameters的嵌套comments_attributes版本。

_params = params.require(:task).permit(:summary, comments_attributes: [:id, :content])
_params.reverse_merge!(user_id: current_user.id)
_params[:comments_attributes].each do |key, value|
  _params[:comments_attributes][key] = value.reverse_merge(user_id: current_user.id, project_id: project.id)
end
_params

很高兴听到是否有更直接的答案!

相关问题