Sunday, March 1, 2009

Rails Callbacks Called Multiple Times - after_save, after_update, after_create, etc.


I was testing the newsfeed functionality I just finished on our application. I began the testing in the console, to ensure the fields were getting updated properly in the database without having to deal with the overhead of testing through my application. Everything worked... that is, until I started testing through the application.

I'm using Rails callbacks, which are basically hooks that allow you to insert logic into the chain of command when handling your models. The following callbacks are currently available:

* after_create
* after_destroy
* after_save
* after_update
* after_validation
* after_validation_on_create
* after_validation_on_update
* before_create
* before_destroy
* before_save
* before_update
* before_validation
* before_validation_on_create
* before_validation_on_update

They're quite convenient and really easy to use. In any event, I noticed my after_save call actually added two identical rows to the database every time I submitted a request through the browser. I couldn't for the life of me figure out what was going on. I was assuming it had something to do with the order in which Rails was handling the objects. I was saving a new model within the callback and wondered if for some reason that was getting called again on the actual model save? Or since I was now going through a controller rather than manually saving an object, did that have something to do with this? Neither turned out to be the case. The real reason was much simpler. Firefox was submitting multiple requests every time I performed an action. This was visible through Firebug. I loaded up IE - and had no problems. I restarted Firefox and it was fixed. Now I need to handle the case when this actually happens to our users too.

2 comments:

Adam said...

I stumbled across this today, a similar thing was happening to me. Turns out it's Firebug that caused the multiple hits for me in Firefox, could that have been the problem for you?

Lefty said...

@Adam - actually I think that's exactly what happened. I ended up having quite a few issues with Firebug... which have not been resolved. Thanks!