How to add globally allowed parameters in Rails?

1

In several resources I use address, I decided to allocate logic in concerns. One need is to add the allowed parameters to the address, see below the concern that should add permission to address_attributes :

module AddressationConcern
  extend ActiveSupport::Concern

  included do
    before_action :address_params
  end

  protected

  def address_params
    params.permit address_attributes: [
      :zip_code, :state, :neighborhood, :city, :street, :number, :complement
    ]
  end
end

Like any concern, I'll call the top of the controller:

class UsersController < ApplicationController
  include AddressationConcern

  ...

  private

  ...

  def user_params
    params.fetch(:user, {}).permit :name, :cpf, :email, :password
  end
end

The question is in the second call of params.permit where I overwrite the contained within the concern.

I do not know a way to do this kind of logic. Does any colleague know a way to do this?

Thank you!

    
asked by anonymous 05.01.2017 / 19:54

1 answer

2

The best alternative I found, meeting my need to abstract the address parameters I use in various resources was to create a module by returning an array with the attributes, see below:

module AddressationConcern
  extend ActiveSupport::Concern

  protected

  def address_attributes
    [:zip_code, :state, :neighborhood, :city, :street, :number, :complement]
  end
end

I call the method in user_params :

class UsersController < ApplicationController
  include AddressationConcern

  ...

  private

  ...

  def user_params
    params.fetch(:user, {}).permit(
      :name, :cpf, :email, :password,
      address_attributes: address_attributes
    )
  end
end

I've talked to many colleagues and friends about this approach. The gem strong_parameters is fantastic, this type of abstraction is unnecessary, but the wanted to implement it for reasons of perfectionism.

    
05.01.2017 / 23:52