How to merge nested attributes in permit + Rails

喜夏-厌秋 提交于 2019-12-23 20:14:17

问题


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

I want to add user_id and project_id in comments_attributes.

user_id    = current_user.id
project_id = project.id

I tried with below but not working

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])

Please help me how can I do this?


回答1:


you will have to use 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])



回答2:


Although an old question, the right answer IMHO is this ->

In Rails 5, instead of .to_h.deep_merge you should use reverse_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])



回答3:


Convert permitted params to hash first, and then deep merge the hash:

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
    ]
)



回答4:


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


来源:https://stackoverflow.com/questions/40981206/how-to-merge-nested-attributes-in-permit-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!