nulltek
nulltek

Reputation: 3337

undefined method `split' for nil:NilClass Rails

I am building a simple asset manager app in Rails 4.2.2 and Ruby 2.2.2. In my asset model I'm using a callback with before_create to call a function generate_asset_number like so

def generate_asset_number
        company = "AMS"
       if Asset.count == 0
        self.asset_number = "#{company}-00001"
       else
        last = Asset.last.asset_number
       end
        number = last.split('-')[1].to_i
        number += 1
        self.asset_number = company + '-' + "%05d" % number
      end
    end

As you can see I'm setting the company variable as a string, evaluating if the Asset.count is 0 then returning the string "AMS-00001", if the Asset.count is not 0 then I'm assigning last to Asset.last.asset_number to pull the last number in the sequence.

Where I'm getting tripped up is with setting the number variable to return the last incident number and call split on it to extract the second part of the array and convert to integer so I can increment it.

When I run this from the console or try to create a new record in the view, I get the following error:

undefined methodsplit' for nil:NilClass`

I'm sure my syntax is off as I'm more of a Ruby Jr.

If anyone can help explain what I need to do to refactor and make this work, I'd appreciate it. If you need further information or if my question is not clear, please let me know.

Upvotes: 0

Views: 2817

Answers (1)

Pavan
Pavan

Reputation: 33542

undefined method split' for nil:NilClass`

The error is because the life of last variable has ended in the if-else loop and you are trying to access last outside the if-else loop in this line number = last.split('-')[1].to_i. You need to tweak your code like this

def generate_asset_number
  company = "AMS"
  if Asset.count == 0
    self.asset_number = "#{company}-00001"
  else
    last = Asset.last.asset_number
    number = last.split('-')[1].to_i
    number += 1
    self.asset_number = company + '-' + "%05d" % number
  end
end

Upvotes: 3

Related Questions