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.
Why are you referring to
current_userin your initialize method? Why not just theuserthat was supplied as an argument to the method?CanCan will call initialize for the current_user when it needs to.