使用cancancan的未定义方法“ admin”

时间:2019-01-31 11:54:35

标签: ruby-on-rails

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

我正在使用has_many through关联。具有3个表-User,Role和UserRole。 UserRole表用于连接用户和角色表。在UserRole表中,我正在存储user_id和role_id。没有名为admin的属性。如何更改以上代码以检查用户是否为管理员?

1 个答案:

答案 0 :(得分:0)

考虑您的角色表具有字段“名称”并且其中包含某些内容(例如“管理员”,“来宾”等)

打开模型app / models / user.rb并在下面添加方法

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

在您的capability.rb中,您可以设置为关注

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