Riptyde4
Riptyde4

Reputation: 5460

Undefined method '+' for nilclass with rails model (active record)

I have a simple model with some integer values (I think, I set them to integer in the migration file at least) and I'm just trying to increment them with a member function of the model but when I try to add to them I'm getting the error "Undefined method `+' for nil:NilClass)

Any tips here??

def take()
    @total -= 1
    User.find(@poster_id).lifetime -= 1
end

def give()
    @total += 1
....

nothing more to it really, it's just simple not working. do I need to cast these somehow? I made sure to initialize the values to 0 upon each instantiation of the model class

Upvotes: 0

Views: 152

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

Firstly, if total is a column in database (and you say it is), then within the instance method of the class you should access it as total, not @total. Secondly, if you want to update the total attribute you should, well, update it :)

def take # notice no () - they are optional
  update(total: self.total - 1)
end

def give
  update(total: self.total + 1)
end

Analogically with poster_id (if, again, it is a column in db) you would do:

user = User.find(poster_id) # notice not @poster_id
user.update(lifetime: user.lifetime - 1)

Upvotes: 1

Related Questions