【问题标题】:How to merge default values into nested params in Rails 5?如何将默认值合并到 Rails 5 中的嵌套参数中?
【发布时间】:2018-08-21 18:28:47
【问题描述】:

我正在拼命尝试将一组默认值合并到我的嵌套参数中。不幸的是,使用 deep_merge 不再适用于 Rails 5,因为它不再继承自 Hash

所以这不起作用

class CompaniesController < ApplicationController

  def create
    @company = current_account.companies.build(company_params)
    if @company.save
      flash[:success] = "Company created."
      redirect_to companies_path
    else
      render :new
    end
  end

private

  def company_params
    params.require(:company).permit(
      :name,
      :email,
      :people_attributes => [
        :first_name,
        :last_name
      ]
    ).deep_merge(
      :creator_id => current_user.id,
      :people_attributes => [
        :creator_id => current_user.id
      ]
    )
  end

end

它给了我这个错误:

ActionController::Parameters:0x007fa24c39cfb0 的未定义方法 `deep_merge'

那怎么做呢?

【问题讨论】:

    标签: ruby-on-rails parameters nested applicationcontroller


    【解决方案1】:

    由于通过查看 docs 在 Rails 5 ActionController::Parameters 中似乎没有类似的 deep_merge 实现,因此您只需简单地执行 .to_h 即可将其首先转换为 ActiveSupport::HashWithIndifferentAccess(即Hash) 的子类:

    to_h() 返回参数的安全 ActiveSupport::HashWithIndifferentAccess 表示,并删除了所有未经许可的键。

    def company_params
      params.require(:company).permit(
        :name,
        :email,
        :people_attributes => [
          :first_name,
          :last_name
        ]
      ).to_h.deep_merge(
        :creator_id => current_user.id,
        :people_attributes => [
          :creator_id => current_user.id
        ]
      )
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-27
      • 2019-09-21
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多