gpt4 book ai didi

ruby-on-rails - 如何将默认值合并到 Rails 5 中的嵌套参数中?

转载 作者:行者123 更新时间:2023-12-04 02:58:07 25 4
gpt4 key购买 nike

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

它给我这个错误:

undefined method `deep_merge' for ActionController::Parameters:0x007fa24c39cfb0

那怎么办呢?

最佳答案

由于在 Rails 5 ActionController::Parameters 中似乎没有类似的 deep_merge 实现,请查看 docs , 然后你可以简单地做 .to_h 把它先转换成 ActiveSupport::HashWithIndifferentAccess (它是 Hash 的子类):

to_h() Returns a safe ActiveSupport::HashWithIndifferentAccess representation of the parameters with all unpermitted keys removed.

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

关于ruby-on-rails - 如何将默认值合并到 Rails 5 中的嵌套参数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51954683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com