ActiveRecord::RecordNotSaved – before_save problem

I am in the middle of an update to my PeopleHub application and I started getting a weird error in my tests (yay for tests): ActiveRecord::RecordNotSaved

Part of the update was changing my before_save code to only do an expensive recalculation when it was required, and after doing so, setting the flag that it used to false (so that next time it didn’t do the expensive recalc). The code looked like this:

def before_save
  if self.do_update
    if x
      write_attribute("the_field", the_field_data)
      self.do_update = false
    elsif y
    end
  end
end

(please excuse the formatting. looks like my css needs attention)

So the end result of this is that in certain cases, the update is never done again. However, note that I am setting self.do_update = false at the end of the block. For those who remember their Ruby fundamentals (d’oh) they will know that if that line is the last that is evaluated in the block, it will return FALSE. As the docs say:

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled.

Whoops. Thanks to Rick Olsen (http://threebit.net/mail-archive/rails/msg38644.html) for the help

Comments are closed.