Cancan Undefined Method 'user' Problems
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
This results in a NoMethodError:
undefined method `user' for #<User:0x000001050914c8>
When I try and edit / update a user. Everything else seems just fine.
Any help appr开发者_如何转开发eciated
Bob
The problem is that
user.try(:user) == user
is basically trying to execute 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.
Try this instead:
can :update, User, :id => user.id
Which is saying "Can update the User model when @user.id
is the same as the current_user.id
."
Your block notation is ambiguous since your block variable |user|
is the same as the user
passed in to the Ability model.
As a side-note for those still getting a grip on Ruby,
can :update, User, :id => user.id
is the same as:
can(:update, User, { id: user.id })
精彩评论