carpamon
carpamon

Reputation: 6623

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?

Upvotes: 11

Views: 7830

Answers (2)

epicrato
epicrato

Reputation: 8418

You can simply do the following:

def post_params
  allowed     = [:name, :age]
  conditional = Some_Condition_Applies ? [:title, :description] : []
  params_list = allowed + conditional
  params.require(:post).permit(params_list)
end

Upvotes: 0

Fred Perrin
Fred Perrin

Reputation: 1134

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.

Upvotes: 33

Related Questions