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

标签 ruby-on-rails parameters nested applicationcontroller

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

相关文章:

ruby-on-rails - rails 分布式并行测试

ruby-on-rails - rails : Missing region error AWS heroku paperclip

video - 调用 360 度视频 Split View的 YouTube 参数

c++ - 如何从单独的函数调用结构?

Java 拖动时始终将 JLabel 保持在 JPanel 上方

javascript - Rails 表示 Javascript 函数的方式

ruby-on-rails - 通过 Ember.js 应用程序将图像上传到 Rails 服务器

c - 两个带有 void 和空参数列表的函数声明

azure - Microsoft.Compute/virtualMachines/extensions' 的段长度不正确

嵌套在自定义 Keras 层内的 Keras 模型