Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `+' for nil:NilClass - Ruby

Currently I have a controller method that will increment 1 every time a user inputs there number in a view form. I'm going to show the code and the error I just want to make sure I'm giving enough background here. So, I have another form that creates a subscriber this model takes in name and phone number but it also has a visit attribute that is a int data type. So the controller method that is giving me the problem, it's function is to increment 1 visit to the Subscriber by finding the number attached to that Subscrier. But when the user types in their phone number it throws this error undefined method `+' for nil:NilClass and I truly and stumped on how to fix it. Here is my code for clarity.

CONTROLLER:

 def visit
  @subscriber = Subscriber.find_by_phone_number(params[:phone_number])
  if @subscriber
   @subscriber.visit += 1
   @subscriber.save
   flash[:notice] = flash[:notice] = "Thank You #{@subscriber.first_name}. You have #{@subscriber.days_till_expired} until renewal"
   redirect_to subscribers_search_path(:subscriber)
  else
   render "search"
  end
 end

ERROR:

enter image description here

I'm not sure what other code would be applicable? let me know if you need more info. Thank You.

like image 266
Bitwise Avatar asked Jun 09 '16 01:06

Bitwise


1 Answers

That's because @subscriber.visit is nil, you need to set it to 0 first.

In your migration you could default it to 0 whenever a subscriber is created, then you don't have to worry about this.

t.integer :visit, default: 0

Or perhaps add the line @subscriber.visit ||= 0 before @subscriber.visit += 1 (which sets it to 0 if nil).

like image 80
Nabeel Avatar answered Oct 22 '22 04:10

Nabeel