Luke
Luke

Reputation: 4925

Issue with CanCan resource loading

I'm using CanCan and I've run into an error I'm having trouble diagnosing.

Some users testing my application have received NoMethodError: undefined method 'where' for nil:NilClass originating from the line noted below.

Under what circumstances would load_and_authorize_resource leave @jobs as nil at that point?

class JobsController < ApplicationController
  load_and_authorize_resource

  def index
    if Job::STATES.include? params[:state]
      if params[:state] == 'in_progress'
        @jobs = @jobs.where(['state = ? or state = ?', params[:state], 'needs_confirmation'])
      else
        ###################################################
        # Error thrown here
        @jobs = @jobs.where(['state = ?', params[:state]])
        ###################################################
      end
    end
  end

end

And the relevent CanCan code:

if user.role? :employee
  can :read, Job do |j|
    (j.employee == user) or ( j.employee == nil )
  end
end

Upvotes: 2

Views: 739

Answers (1)

Michael De Silva
Michael De Silva

Reputation: 3818

You should be doing Job.where(...) - you are getting that error because you are indeed calling where on a nil instance variable. I personally do not rely too much on load_resource, there's no harm in being explicit.

Upvotes: 1

Related Questions