1

I've got a Rails project using Devise together with the really awesome Pundit Gem. I'm using three different roles - Superadmin, Admin and User.

I was wondering if it's possible to somehow define that the superadmin has all the rights that the admin has plus more. So that I don't have to write <% if current_user.admin? || current_user.superadmin? %> in my views anymore.

Bergrebell
  • 4,263
  • 4
  • 40
  • 53

1 Answers1

3

The fact that you are using if current_user.admin? || current_user.superadmin? in your views is a particularly stinky code smell that indicates that you are not using the authorization layer properly.

You should be using:

<% if policy(@post).update? %>
  <%= link_to "Edit post", edit_post_path(@post) %>
<% end %>

And defining the rules in your policies - not spreading the authorization logic (who can do what) all over the place.

class ApplicationPolicy
  # ...
  def update?
    admin?
  end

  private 

  def admin?
    user.admin? || user.superadmin?
  end
end 

class PostPolicy < ApplicationPolicy
  def update?
    super || record.author == user
  end
end

If you are using a role library like Rolify you can also simplify this by giving the superadmins both an admin and superadmin role:

@user.add_role(:admin)
@user.add_role(:superadmin)
@user.has_role?(:admin) # true
max
  • 96,212
  • 14
  • 104
  • 165