我拼命尝试将一组默认值合并到我的嵌套参数中。不幸的是,使用
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”
那么如何才能做到呢?
由于在 Rails 5
deep_merge
中似乎没有类似的 ActionController::Parameters
实现,通过查看这个 docs,那么你可以简单地执行 .to_h
将其首先转换为 ActiveSupport::HashWithIndifferentAccess
(即Hash
) 的子类:
to_h() 返回参数的安全 ActiveSupport::HashWithIn DifferentAccess 表示形式,并删除所有未经允许的键。
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
with_defaults
(reverse_merge
的别名)的方法,它可以实现你想要的功能:
private
def company_params
params.require(:company).permit(
:name,
:email,
:people_attributes => [
:first_name,
:last_name
]
).with_defaults(
:creator_id => current_user.id,
:people_attributes => [
:creator_id => current_user.id
]
)
end