如何在permit + Rails中合并嵌套属性 [英] How to merge nested attributes in permit + Rails
本文介绍了如何在permit + Rails中合并嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
params.require(:task).permit(:summary, comments_attributes: [:id, :content])
我想在 comments_attributes 中添加 user_id 和 project_id.
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?
推荐答案
虽然是个老问题,但恕我直言,正确答案是这个 ->
Although an old question, the right answer IMHO is this ->
在 Rails 5 中,您应该使用 reverse_merge 而不是 .to_h.deep_merge
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])
这篇关于如何在permit + Rails中合并嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文