Rails Can Can Ability Class For Multiple Devise Models
Asked Answered
S

1

10

I was wondering how I can define an ability class and serve that ability class depending on the user that has logged in.

I am using Active Admin, Can Can and Devise and I have successfully created a User and an AdminUser models.

I have this in my ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if (user)
      can :manage, Item
    end
  end
end

Now I have used this wiki entry to determine that we can indeed define a custom ability file and use that instead of the ability.rb:

https://github.com/ryanb/cancan/wiki/changing-defaults

But what I wanted to do is, be able to use ability.rb if a "non-admin user" is signed in and a custom abilty if a user admin is signed in.

Side Question: Could it be done such that I don't need a custom one and I could set permissions in one ability.rb file?

Sauer answered 26/10, 2011 at 2:21 Comment(1)
Ah, you're right. I didn't notice that you had used a separate class for User and AdminUser. You should be able to change the class used by Active Admin, but not being a user of that system, I'm not sure exactly where that is. Probably should check your initializers though.Marquittamarr
D
12

I've never really used ActiveAdmin, so I'm not entirely sure if I'm missing something, but it doesn't seem like that framework relies on CanCan. That's why I'm assuming you're defining a current_ability method like explained in the wiki and it's instantiated with Ability.new(current_user).

If that's the case, and your current_user can be either a User or an AdminUser, then there's no problem in checking for that in the Ability class:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.kind_of? AdminUser
      can :manage, Item
    elsif user.kind_of? User
      can :read, Item
    end
  end
end

You can simply take a look at the user's type and change the rules accordingly. You can also use is_a? instead of kind_of? for stricter checking, but it's probably not required and might cause issues if you decide to do inheritance later on.

Another way you could check is by defining an admin? method in both models. This might be a better way to do it, since explicit type checking is not very popular in ruby -- it often limits your choices. It might look like this:

class User < ActiveRecord::Base
  def admin?
    false
  end
end

class AdminUser < ActiveRecord::Base
  def admin?
    true
  end
end

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    if user.admin?
      can :manage, Item
    else
      can :read, Item
    end
  end
end
Dermatologist answered 27/10, 2011 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.