Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 290
Nicolas Garnil Avatar asked Oct 10 '14 19:10

Nicolas Garnil


1 Answers

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.

like image 146
Fred Perrin Avatar answered Oct 13 '22 01:10

Fred Perrin