0

Hello stackoverflowers!!!!

I have 2 models:

models/user.rb

class User
  has_many :colleagues

  before_save :give_points

  private

  def give_points
    if self.name == "Jordie"
      colleague1 = Colleague.find_by_name("Ann")
      colleague2 = Colleague.find_by_name("Beth")
      colleague1.increment!(:bonus, by = self.points)
      colleague1.decrement!(:bonus, by = self.points)
    end
  end
end

models/user.rb

class Colleague
  belongs_to :user
end 

Matter fact I want to increment and decrement Ann and Beth when the Jordie gives them bonuses.But I get the following:

undefined method `increment!' for nil:NilClass

What's the best way to handle this.I'm really confused by how to retrieve a specific object and increment it's attribute

blawzoo
  • 2,465
  • 4
  • 19
  • 24

1 Answers1

2

In general, getting

undefined method "something" for nil:Class

Means that the receiver is nil ! Did you check that you object colleague1 was not nil by using a debugger ? If it is not nil it means that an internal instruciton of the increment! is also called increment and I have serious doubts about this.

What I find suspicious in your code is that you use by = self.points in you function call. In ruby you either write :by => self.points ( or by: self.pointswhen you talk ruby 1.9.x) when a method expects a Hash as last argument and you know it expects :byas one of the keys, or just self.pointsand according to rails doc the signature of increment is:

increment(attribute, by = 1)

Which means you should use this method by calling:

colleague1.increment!(:bonus, self.points)
rpechayr
  • 1,282
  • 12
  • 27
  • indeed I find with the debugger that colleague1 is nil.That's curious.Do "find_by_name" returns nil objects? I'm really confuse – blawzoo Feb 29 '12 at 13:10
  • `find_by_*` accessors do return `nil` objects when they don't find it. You just need to use `find_by_name!` if you want to throw an `ActiveRecord::RecordNotFound` exception when necessary but you need to handle it. I think this answer is the right answer for this question. PLease consider granting this answer "the" answer of the question ;) – rpechayr Feb 29 '12 at 13:18
  • You right rpechayr, thanks for helping.I accept your answer.I still don't know why colleague1 is nil despite it's in the database. That's crazay!!! – blawzoo Feb 29 '12 at 13:53