3

I am desperately trying to merge a set of default values into my nested params. Unfortunately, using deep_merge no longer works in Rails 5 since it no longer inherits from Hash.

So this does not work:

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

It gives me this error:

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

So how can it be done?

Tintin81
  • 9,821
  • 20
  • 85
  • 178

1 Answers1

6

Since there seems to be no similar implementation of deep_merge in Rails 5 ActionController::Parameters by looking at this docs, then you can just simply do .to_h to convert it first into a ActiveSupport::HashWithIndifferentAccess (which is a subclass of a 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
Jay-Ar Polidario
  • 6,463
  • 14
  • 28