Felix
Felix

Reputation: 5619

undefined method `empty?' for nil:NilClass how to avoid it

Hi Together I've got this code:

 @coursesFound = @user.available_courses
@courses = []

for course in @coursesFound do
  @courseInGroups = course.user_groups
  for group in @courseInGroups do
    @group = UserGroup.find group.id
    if @group.users.map { |u| u.id }.include? @user.id
      @courses << course
      break
    end
  end
end

# Wenn ein Kurs keiner Gruppe hinzugefügt wurde
if @courseInGroups.empty?
  @courses << course
end

on my debian vm it works fine but on my live system I got this error:

undefined method `empty?' for nil:NilClass

How can I avoid this?

Upvotes: 6

Views: 29413

Answers (5)

bigsolom
bigsolom

Reputation: 2349

You can use the try method to Avoid this error:

@courseInGroups.try(:empty?)

This won't throw an error if @courseInGroups was nil.

Upvotes: 4

Igor Cardoso
Igor Cardoso

Reputation: 1

You can put the ? before the dot of the empty:

if @courseInGroups?.empty

Upvotes: 0

Nitin
Nitin

Reputation: 7366

You need to properly initialize your object as well.

@courseInGroups = course.user_groups || []

You won't get nil:NilClass error any more if you initialize properly.

To get rid of nil:NilClass error you can use other answer. like try etc.

Upvotes: 2

halfbit
halfbit

Reputation: 3939

And don't forget blank? when using rails. Here you find a good overview of all methods with or without rails.

I did not analyze your code, it's just for you, me and others that do not use this methods often, mix them up and then come here - just to remember: empty? is not blank?.

Upvotes: 2

j-dexx
j-dexx

Reputation: 10406

If this @coursesFound = @user.available_courses returns an empty activerecord relation.

Then this won't execute

for course in @coursesFound do
  @courseInGroups = course.user_groups
  for group in @courseInGroups do
    @group = UserGroup.find group.id
    if @group.users.map { |u| u.id }.include? @user.id
      @courses << course
      break
    end
  end
end

Which means when you get here @courseInGroups is nil

if @courseInGroups.empty?
  @courses << course
end

So your quick fix would be

if @courseInGroups && @courseInGroups.empty?
  @courses << course
end

Upvotes: 11

Related Questions