Search code examples
ruby-on-railsnomethoderror

undefined method `any?' for nil:NilClass


This seems like a simple issue, but I can't for the life of my pinpoint the problem.

Extracted Source: Show.Html.Erb

  <% if @jobs.any? %>

users_controller.rb

def show
    if current_user.role == 4
        @jobs = Job.where(jsender_id: current_user.id).order('created_at DESC')
    else
    end
end

My Jobs table is empty which made me first assume that @jobs was being instantiated as 'Nil' since there were no records in the DB. I created a few records but still I am getting the No Method error. Am I missing something here?

Job.rb for good measure:

class Job < ActiveRecord::Base
   belongs_to :jsender, :class_name => 'User'
   belongs_to :jrecipient, :class_name => 'User'
end

Solution

  • You're only setting @jobs when current_user.role == 4, so we can say concretely that current_user.role is not 4. It's impossible. If it were, @jobs could not be nil, as .where cannot return nil, it returns an empty array if there are no matched records.

    We can't help you further, except to tell you to figure out what the value of current_user.role is, and why it isn't what you expect.