Even though record.valid? is true, are you getting false for record.save, and record.save! throws an ActiveRecord::RecordNotSaved error? This one has burned me a couple of times so this time I’m writing it down.

The solution: Check your before and after callbacks! By returning false on any of these callbacks, you are in effect returning false on “save”. Here’s an example:

1
2
3
4
5
before_create :set_defaults

def set_defaults
  self.something = false
end

In a ruby method, if you don’t specifically “return” a value, you will always return the result of the last line of the method. In this case, you’re returning the value of self.something, which you just set to “false”. The fix is simple:

1
2
3
4
def set_defaults
  self.something = false
  true
end

The same thing can happen in your controllers. By unintentionally returning false, in an action or in a before_filter, you can end up with some confusing results.

Sorry, comments are closed for this article.