Search code examples
ruby-on-railsrefactoringdryautomated-refactoring

Rails: How can i refactor my controller params code


I need to refactor this private method. Codeclimate is giving me a error msj because the line of the params is too long. How can i refactor it?

def base_plan_params
    params[:base_plan][:debit_date_attributes]&.merge!(
      account_id: current_account.id,
      _destroy: params[:base_plan][:debit_date_attributes][:date_type].blank?,
    )
    params.require(:base_plan).permit(
      :code,
      :cover,
      :name,
      :products,
      :pricing_model,
      :metered,
      debit_date_attributes: %i[id account_id date_type value _destroy],
    )
  end```

Solution

  • making an assumption here about which CodeClimate "too long" error is being triggered, as you didn't clarify.

    You could form the permitted params into an array, like this:

    permitted_params = [:code, :cover, :name, :products, :pricing_model, :metered]
    params.require(:base_plan).
           permit(*permitted_params, 
                  debit_date_attributes: %i[id account_id_data_type value _destroy],)
    

    Personally I wouldn't bother, but if the CodeClimate warning troubles you, then this solution would probably work.