![](/img/trans.png)
[英]Rails admin and cancancan, undefined method `new' for nil:NilClass
[英]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.