0
votes
class Ability
include CanCan::Ability

  user ||= User.new # guest user (not logged in)

  if user.admin
    can :manage, :all
  else
    can :read, :all
  end
end

I am using has_many through association. Having 3 tables - User, Role and UserRole. UserRole table is used to connect users and roles tables. In UserRole table I am storing user_id and role_id. There is no attribute named admin. How do I change the above code to check if the user is admin?

1
Do you use rolify gem for roles? - Vasilisa
No. I have used gem 'cancancan' - Vijay
@Vasilisa above must be having rolify gem for sure. Sneha check once in gemfile whether it contains rolify - ray
@Sneha, I understood about cancancan. Did you implemented your own roles, or is it from rolify gem? Check Gemfile for it, as ray suggested - Vasilisa
User.instance_methods.map(&:to_s).select { |x| x.match /admin/ } in rails console, what does it provide? - ray

1 Answers

0
votes

consider your role table has field 'name' and it have content some thing ('admin','guest',etc)

open your model app/models/user.rb and add method below

def admin?
  self.roles.find_by_name('admin') ? true : false
  # since one user has many roles you should find by role name
  # whether it has role with name admin
  # if it find the record the method will return true 
end

in your ability.rb you can set like follow

class Ability
include CanCan::Ability

  user ||= User.new # guest user (not logged in)

  if user.admin?    # I changed admin to admin? to match method above
    can :manage, :all
  else
    can :read, :all
  end
end