Cameron Bass Cameron Bass - 10 months ago 82
Ruby Question

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

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.


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


enter image description here

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


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