Cancan未定义方法“用户”问题 [英] Cancan Undefined Method 'user' Problems
问题描述
我遇到了在我的cancan控制器中定义用户权限的问题:
I'm running into problems defining user permissions in my cancan controller:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :admin
can :manage, :all
else
can :read, :all
can :update, User do |user|
user.try(:user) == user
end
end
end
end
这会导致NoMethodError:
This results in a NoMethodError:
undefined method `user' for #<User:0x000001050914c8>
当我尝试编辑/更新用户时。
When I try and edit / update a user. Everything else seems just fine.
任何帮助表示赞赏
Bob
推荐答案
问题是
user.try(:user) == user
基本上是在尝试执行 user.user == user
如果您所讨论的User实例是登录用户,您似乎只想让用户更新User模型属性。
Looks like you're trying to only let users update the User model attributes if the User instance in question is the logged-in user.
尝试以下操作:
can :update, User, :id => user.id
说可以在 @user时更新用户模型.id
与 current_user.id
相同。
您的块符号是模糊的,因为您的块变量 | user |
与传递给Ability模型的 user
相同。
Your block notation is ambiguous since your block variable |user|
is the same as the user
passed in to the Ability model.
作为那些仍然对Ruby有所了解的人的补充说明,
As a side-note for those still getting a grip on Ruby,
can :update, User, :id => user.id
等同于:
can(:update, User, { id: user.id })
这篇关于Cancan未定义方法“用户”问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!