ruby-on-rails - 如何将强参数中的嵌套属性与 has_many 关联合并
问题描述
在我的 rails 6 应用程序控制器中,我有以下强参数:
params.require(:item).permit(:summary, tasks_attributes: [:id, :name])
我想将以下内容合并到任务属性中:
user_account_id: user_account.id
account_id: current_account.id
我尝试了以下但没有成功:
params.require(:item).permit(:summary, tasks_attributes: [:id, :name])
.reverse_merge(tasks_attributes: [user_account_id: user_account.id, account_id: current_account.id]
如果我尝试
.reverse_merge(account_id: current_account.id)
它成功地合并到项目中,但没有运气尝试将其纳入任务属性。其他帖子提到了 reverse_merge,但假设它们在 has_one/belong to 关系中工作。
如果在强参数中不可能,我将不得不在拉入参数后执行以下操作:
@item.tasks.each { |task| task.user_account_id = user_account.id }
解决方案
您需要遍历嵌套属性并合并每个属性哈希:
def item_params
params.require(:item)
.permit(:summary, tasks_attributes: [:id, :name])
.tap do |wl|
wl.tasks_attributes.each do |hash|
hash.reverse_merge!(
user_account_id: user_account.id,
account_id: current_account.id
)
end
end
end
AFAIK ActionController::Parameters 并没有真正的内置实用程序来执行您想要的操作,并且它确实超出了强参数的设计范围,即将参数列入白名单以进行批量分配。
推荐阅读
- django - Djnago 发布“喜欢”功能问题
- javascript - JSON.parse 在我的字符串上返回 undefined
- javascript - 有什么方法可以复制 div 的呈现 HTML?
- python - 为什么我的 2D FFT 卷积取代了结果?
- php - 在 Laravel 中以逗号分隔的列搜索数组值
- azure-application-insights - Application Insights Dashboard - 设置图表维度?
- authentication - 无法使用 UsernameAndPasswordToken 进行身份验证并使用 Spring Security 设置 Cookie
- ruby-on-rails - 如何使用其他字段计算数据库字段?
- java - 过滤器重定向和登录后加载下一页
- php - 完整性约束违规:1452 无法添加或更新子行:外键约束