6

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?

Felix
  • 5,452
  • 12
  • 68
  • 163

5 Answers5

11

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
j-dexx
  • 10,286
  • 3
  • 23
  • 36
4

You can use the try method to Avoid this error:

@courseInGroups.try(:empty?)

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

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
bigsolom
  • 2,309
  • 1
  • 19
  • 15
2

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.

Fred Willmore
  • 4,386
  • 1
  • 27
  • 36
Dipak Gupta
  • 7,321
  • 1
  • 20
  • 32
  • Just in case "course.user_groups" will return an ActiveRecord relation, which is different from "[]" which is an array. Using "**Course.none**" (_Model.none_) would return an **empty** ActiveRecord relation, and that would be better instead of "[]". – Hugo Nov 26 '17 at 04:18
2

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?.

halfbit
  • 3,773
  • 2
  • 34
  • 47
0

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

if @courseInGroups?.empty
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61