Search code examples
ruby-on-railsruby-on-rails-pluginscancan

Nil in CanCan initialize parameter in ability.rb model


I'm following the tutorial from Ryan B, but I got something wrong when trying to inspect the user's role.

Why I got a nil initialize parameter when I inspect it. Are there any connection between the initialize parameter with the Person Object, in Ryan's tutorial is using 'user' parameter on initialize method and User Model. Am I forgetting something basic here? These are my codes, Thanks!

class Ability 
  include CanCan::Ability

  def initialize(person)
    raise person.inspect
    can :read, :all
  end
end

Solution

  • Most likely there is no logged in user when you are running this code. You need to create some sort of guest user to check permissions against non logged in users

      def initialize(person)
        user ||= User.new
        if user.role? :somerole
          can :read, :all
        else
         #whatever guest can do
        end
      end