One role per user CanCan, undefined method 'role' problem
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 开发者_如何学JAVAis 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.
the problem is that you defined role?
method but in ability.rb
you call the role
method which is of course undefined
the proper way to do that will be
def initialize(user)
if user.role? "admin"
can :manage, :all
else
can :read, :all
end
end
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:
def current_ability
if session[:user_id] # Replace with the method to get the user from your session
user = User.find(session[:user_id])
else
user = User.new
end
@current_ability ||= Ability.new(user)
end
精彩评论