2

My application has 3 roles: :admin, :manager, :editor and allows all of them to create products. But these users do not have the same permitted params.

:admin => params.require(:product).permit(:a, :b, :c, :d)
:manager => params.require(:product).permit(:a, :c, :d)
:editor => params.require(:product).permit(:b, :d)

I don't like to delete the keys because the logic is very complex and it's hard to read. I'm looking the way define the logic by action and role.

How can I permit the params by their role? What is the best way to do it? Is there any way like Pundit with authorization?

Thank you so much.

Note: [:a, :b, :c, :d] is dynamically generated by checking policies using Pundit. Is there any extension for Pundit?

fongfan999
  • 2,565
  • 1
  • 12
  • 21

3 Answers3

2

I usually create module ParamsSanitizer inside app/services.

And in the controller, I call like this: ParamsSanitizer::Products.sanitize(params, current_user)

All logics will be define inside these classes.

J. Doe
  • 36
  • 4
1

Set attributes to the constant based on their role.

ADMIN_ATTRIBUTES = [:a, :b, :c, :d]
MANAGER_ATTRIBUTES = [:a, :c, :d]
EDITOR_ATTRIBUTES = [:b, :d]

Then you can add three method for permitting params and call them based current user role.

def admin_params
  params.require(:product).permit(ADMIN_ATTRIBUTES)
end

def manager_params
  params.require(:product).permit(MANAGER_ATTRIBUTES)
end

def editor_params
  params.require(:product).permit(ADITOR_ATTRIBUTES)
end
Junan Chakma
  • 651
  • 7
  • 14
  • Thanks, This is just for action `create`, the permitted params in action `update` is not as same as `create`. I have to create 3 more methods? :( – fongfan999 Jan 13 '18 at 12:03
  • Why permitted params for `update` is different? it is totally different or just less permitted attributes then `create`'s permitted attributes? – Junan Chakma Jan 13 '18 at 12:14
  • Because of business logic :(. Permitted params are based on product's status, so it could be totally different – fongfan999 Jan 13 '18 at 12:59
0

I'm not sure if this is what you want, but you can do something like

def product_params
  case current_user.role
  when :admin
    params.require(:product).permit(:a, :b, :c, :d)
  when :manager
    params.require(:product).permit(:a, :c, :d)
  when :editor
    params.require(:product).permit(:b, :d)
  end
end
Anurag Aryan
  • 611
  • 6
  • 16
  • Thanks, This is just for action `create`, the permitted params in action `update` is not as same as `create`. I have to add 3 more cases? :( – fongfan999 Jan 13 '18 at 12:04