CanCan 每个用户一个角色,未定义方法“角色”;问题
真的很困惑。角色按照每个用户一个角色的方法设置并正常工作。我的用户模型如下。
class User < ActiveRecord::Base
ROLES = %w[admin landlord]
def role?(role)
roles.include? role.to_s
end
end
当我将权限添加到我的能力模型时,我收到以下错误。
undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x10433a5e0>
我的能力模型如下。
class Ability
include CanCan::Ability
def initialize(user)
if user.role == "admin"
can :manage, :all
else
can :read, :all
end
end
end
这是我在终端中看到的。
NoMethodError (undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x1044d46a8>):
app/models/ability.rb:5:in `initialize'
app/controllers/application_controller.rb:6:in `new'
app/controllers/application_controller.rb:6:in `current_ability'
正如你所知,我只是在学习!即使朝着正确的方向轻推也会令人惊奇。谢谢。
Really confused. Roles are set up and working nicely following the one role per user method. My user model is below.
class User < ActiveRecord::Base
ROLES = %w[admin landlord]
def role?(role)
roles.include? role.to_s
end
end
It is when I add the permissions to my ability model I get the following error.
undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x10433a5e0>
My Ability model is below.
class Ability
include CanCan::Ability
def initialize(user)
if user.role == "admin"
can :manage, :all
else
can :read, :all
end
end
end
And here is what I see in terminal.
NoMethodError (undefined method `role' for #<ActionDispatch::Session::AbstractStore::SessionHash:0x1044d46a8>):
app/models/ability.rb:5:in `initialize'
app/controllers/application_controller.rb:6:in `new'
app/controllers/application_controller.rb:6:in `current_ability'
As you can tell I am just learning! Even a nudge in the right direction would be amazing. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在将会话传递给 CanCan。您需要传递当前登录的用户。我猜测在您的 Rails 书中的解释中,应该有一种方法可以从变量会话访问该用户。将该用户作为该功能的参数传递。
如果用户未登录,我将发送一个新用户。
您需要将代码重构为:
You are passing a session to CanCan. You need to pass the user that is currently signed in. Im guessing in the explanation of your rails book, there should be a way to access that user from the variable session. Pass that user as an argument to the ability.
If a user is not signed in, I would send a new User.
You would need to refactored the code, to something like:
问题是您定义了
role?
方法,但在ability.rb
中您调用了role
方法,这当然是未定义的正确方法那将是
the problem is that you defined
role?
method but inability.rb
you call therole
method which is of course undefinedthe proper way to do that will be