11

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?

carpamon
  • 6,515
  • 3
  • 38
  • 51

2 Answers2

33

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.

Fred Perrin
  • 1,124
  • 2
  • 17
  • 23
  • 2
    `list_params_allowed += [:role] if current_user.admin?` sounds better especially if u might want to add more parameters later. – rubyprince Oct 10 '14 at 20:13
  • @rubyprince Thanks for your comment. Can you explain why it's better than my solution with ````<<```` for each param ? (just to understand) Is it faster or more 'ruby' way... ? – Fred Perrin Oct 10 '14 at 20:20
  • i would say it is more ruby way and more maintainable. I could write like this `admin_only_parameters = [:role]; list_params_allowed += admin_only_parameters if current_user.admin?` and just change the `admin_only_parameters`. – rubyprince Oct 10 '14 at 20:43
  • Maybe that's a mistake. << is more elegant and faster, as it doesn't creates new array, but modifies self. – Alexander Karmes Oct 10 '14 at 20:44
  • @yukke, `<<` is definitely faster, but it will be of any effect if the code is in a loop of 10000 times or more. and also thnk how code will look if there are more than 3 admin_only_parameters. – rubyprince Oct 10 '14 at 20:56
  • 2
    Yeah, but with 1 element's case `allowed_params << :role` looks more clearly than `allowed_params += [:role]`. And in any case such constructions are easy to refactor. – Alexander Karmes Oct 10 '14 at 21:14
  • 1
    In the gem version of Strong Parameters (for Rails 3.2) at least, permit will not accept an array of values. You need to do this instead: `params.require(:user).permit(*list_params_allowed)` that turns the array into arguments for the method. – Brendon Muir Aug 30 '16 at 07:16
0

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
drjorgepolanco
  • 7,479
  • 5
  • 46
  • 47