Search code examples
ruby-on-railsauthorizationpundit

Using Pundit for Rails 5 Authorization with two different user tables (User and Admin)


If using Pundit for authorization in a Blog app, Devise for Authentication with different user tables for User and Admin, how can a Policy for Posts be implemented where:

  • Users can update their own posts
  • Admins can update anyone's post

In the examples I've seen online, there does not seem to be a provision for handling multiple user tables such as Admin and User.

Having a UserPolicy and AdminPolicy that are specific to their respective tables is straightforward, but how does the PostPolicy implement a feature something like:

def initialize(COULD BE A USER OR ADMIN, scope)
  @user = USER OR ADMIN
  @scope = scope
end

def update?
  return true if user is either resource.user or ANY ADMIN
end

Solution

  • Because they are in different tables, I assume User and Admin are also in different classes, you can just use is_a? to check.

    def update?
      @user == resource.user || @user.is_a?(Admin)
    end