首页 > 解决方案 > 如何将强参数中的嵌套属性与 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 }

标签: ruby-on-railsparameters

解决方案


您需要遍历嵌套属性并合并每个属性哈希:

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 并没有真正的内置实用程序来执行您想要的操作,并且它确实超出了强参数的设计范围,即将参数列入白名单以进行批量分配。


推荐阅读