设计“current_user” CanCan 能力中的方法结果为“未定义的方法”错误
我正在尝试在我的 Rails3+mongoid 应用程序中使用带有 CanCan 角色的 Devise 授权。 现在我必须限制用户编辑事件的权限,因此只有他们的作者才能执行此操作。事件的作者由该行确定:
<%= f.hidden_field (:author, :value =>current_user.email) %>
因此,现在在 CanCan 的能力文件中,我尝试使用此代码:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role? :admin
can :manage, :all
else
can :read, :all
end
if
user.role?(:normal)
can :create, Event
can :update, Event do |event|
event.try(:author) == current_user.email
end
can :create, Comment
can :update, Comment do |comment|
comment.try(:author) == current_user.email
end
end
end
end
但这会导致我出现此错误:
# 的未定义局部变量或方法“current_user”
然后我尝试更改
can :update, Event do |event|
event.try(:author) == current_user.email
为
event.try(:author) == Devise.current_user.email
但会导致此错误
Devise:Module 的未定义方法“current_user”
那么,我应该做什么以及如何从ability.rb 中调用“current_user”方法?预先感谢您提供任何提示。
I'm trying to use Devise authorisation with CanCan roles in my rails3+mongoid app.
Now I have to limit users access to edit the events, so only their author could do this. Author of the event is determined by that line:
<%= f.hidden_field (:author, :value =>current_user.email) %>
So, now in CanCan's Ability file i'm trying to use this code:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role? :admin
can :manage, :all
else
can :read, :all
end
if
user.role?(:normal)
can :create, Event
can :update, Event do |event|
event.try(:author) == current_user.email
end
can :create, Comment
can :update, Comment do |comment|
comment.try(:author) == current_user.email
end
end
end
end
But this results me with this error:
undefined local variable or method `current_user' for #
Then i've tried to change
can :update, Event do |event|
event.try(:author) == current_user.email
to
event.try(:author) == Devise.current_user.email
but that results with this error
undefined method `current_user' for Devise:Module
So, what should I do and how can I call for `current_user' method from ability.rb? Thank you in advance for any tips.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么在初始化方法中引用
current_user
?为什么不只是作为该方法的参数提供的user
?CanCan 将在需要时为 current_user 调用初始化。
Why are you referring to
current_user
in your initialize method? Why not just theuser
that was supplied as an argument to the method?CanCan will call initialize for the current_user when it needs to.