簡體   English   中英

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

[英]Undefined method `admin' using cancancan

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關聯使用has_many through 具有3個表-User,Role和UserRole。 UserRole表用於連接用戶和角色表。 在UserRole表中,我正在存儲user_id和role_id。 沒有名為admin的屬性。 如何更改以上代碼以檢查用戶是否為管理員?

考慮您的角色表具有字段“名稱”,並且其中包含一些內容(“ admin”,“ guest”等)

打開模型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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM