Rails caching woes

I’ve just been going round in circles trying to work out why my caching sweeper in rails was not working after I changed the relationship between two models.

I have a post and comment model which was a has_many/belongs_to relationship which I recently change to has_and_belongs_to_many. That part was fine but when I deployed to staging when I tried to delete a comment I was getting NoMethodError on a nil object error. Ummm. So after spending a good few hours banging my head against the brick wall conveniently located on my desk for moments such as this and invoking the “I really like rails but some bits of it …” mantra I finally worked it out.

When the object is passed to the after_destroy method the object has already been deleted from the database and given that ActiveRecord lazily loads, when I tried to access the post object from the comment object it did a dummy spit because it’s trying to load an object via another object that doesn’t exist.

So I changed the method to before_destroy and all is good. You might argue this is incorrect as you would want to make sure that the object has actually been deleted before the cache is invalidated but in all honesty I don’t care. The worst case that can happen is that I invalidate and object from the cache that still exists.

Problogger

In the name of winning two monitors from here I’m writting this blog post. Good luck to me!

Oh what fun it would be if I won.