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:
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.