Tin*_*n81 3 parameters nested ruby-on-rails applicationcontroller
我拼命地尝试将一组默认值合并到我的嵌套参数中。不幸的是, 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
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误:
ActionController::Parameters:0x007fa24c39cfb0 的未定义方法`deep_merge'
那么怎么做呢?
由于通过查看此docsdeep_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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
807 次 |
| 最近记录: |