Rails 3 observers can be tricky. You probably already heard a thousand times how to deal with undefined id issue and how transactions are handled, so let’s take a quick example that can be google’d in just a couple of seconds.
classUserObserver<ActiveRecord::Observerdefafter_commit(user)returnunlessuser.send(:transaction_include_action?,:create)# some code that should be executed only on create, after transaction is committedendend
So what’s wrong with this example? Nothing. But let say SuperUserhas_manyusers. Some example code:
# obviously we need super user firstSuperUser.first.users.create(name:"boo")# this won't create record, due validation#<RuntimeError: #<User id: nil, name: "boo", owner_id: 1, created_at: nil, updated_at: nil> | Persisted: false>=>#<User id: nil, name: "boo", owner_id: 1, created_at: nil, updated_at: nil>
Hell yeah, observer code executed perfectly, even this is not what we would normally expect. I was quite surprised with this behavior, I recommend checking out ActiveRecord::Transactions internals, if I find some time I will write a follow-up to this, cheers.