【问题标题】:How to merge nested attributes in permit + Rails如何在permit + Rails中合并嵌套属性
【发布时间】:2016-12-05 18:47:09
【问题描述】:
params.require(:task).permit(:summary, comments_attributes: [:id, :content])

我想在 cmets_attributes 中添加 user_idproject_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])

请帮帮我,我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    虽然是个老问题,但恕我直言,正确答案是这个 ->

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这在 Rails 5 中是如何工作的?似乎deep_merge 不再是ActionController::Parameters 的子类。我在 Rails 5 中收到 deep_mergeundefined method 错误。
      • @Tintin81 检查新答案。万事如意
      • @Tintin81 尝试使用reverse_merge
      【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-28
          • 1970-01-01
          相关资源
          最近更新 更多