Search code examples
ruby-on-railsauthorizationpundit

The elegant way to permit parameters by current user's role in Ruby on Rails?


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?


Solution

  • 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.