3

我拼命尝试将一组默认值合并到我的嵌套参数中。不幸的是, usingdeep_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”

那么怎么做呢?

4

1 回答 1

5

由于通过查看此文档deep_merge在 Rails 5 中似乎没有类似的实现,因此您可以简单地将其首先转换为 a (这是 a 的子类):ActionController::Parameters.to_hActiveSupport::HashWithIndifferentAccessHash

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
于 2018-08-21T18:40:00.677 回答