Search code examples
ruby-on-railsstrong-parameters

Strong Parameters: How to permit parameters using conditions


I wan't to permit certain parameters depending on the current user's role.

E.g: only permit the role attribute if the user is an administrator.

Is this possible?


Solution

  • Yes, it's possible.

    You can do something like this :

    def user_params
      # List of common params
      list_params_allowed = [:email, :title, :last_name, :first_name, :phone]
      # Add the params only for admin
      list_params_allowed << :role if current_user.admin?
      params.require(:user).permit(list_params_allowed)
    end
    

    This way, if later you have new params, you only have to add in one list (avoids error).

    If you have more than one param to add for the admin, you can do this like this :

    list_params_allowed << :role << other_param << another_param if current_user.admin?
    

    Hope this help.