Transactions and new_record?

While working with the ActiveRecord method ‘new_record?’ and Transactions I ran into an odd issue after I had run a few objects through a Transaction. Although the transaction had rolled back and thus not saving the record, running ‘object_instance.new_record?’ resulted in a return of false as if the record had been saved to the database.

I also found the same issue recorded here: http://squarewheel.wordpress.com/2008/06/11/new_record/

Here is example code where the error will happen. Tested with Rails 3.1.0 & ActiveRecord 3.1.0

For this example I generated a new project

rails new rollback
rails g model Cat name:string purrr:string age:integer lives_left:integer
rake db:migrate

Then I can kick up a console session:

Cat.transaction do
  @cat = Cat.new(name: 'Professor Wellington', purrr: 'meooow', age: 17, lives_left: 6)
  @cat.save
  raise Exception
end
#=> throws a big error

@cat.persisted?
#=> true
@cat.new_record?
#=> false
@cat.inspect
#=> <Cat id: 1, name: \"Professor Wellington\", purrr: 'meooow', age:
17, lives_left: 6, created_at: \"2013-02-02 00:20:44\", updated_at: \"2013-02-02 00:20:44\">
Cat.count
#=> 0

So even though the Professor was never actually saved to the database the ruby model acts as if it has been.

I didn’t revisit the issue until publishing this post (the current date is Feb 1, 2013) and have since found that in Rails 3.1.10 the issue has been resolved. I don’t know at what patch level the fix happend but it is no longer an issue.