Is there a way to ensure that a given before_save callback is executed after all other before_save callbacks in ActiveRecord short of actually ordering them so in the code?
I’m writing an external library that includes some before_save functionality but in order to be effective it really needs to be called after all others. I can get around it but it involves giving up dirty attributes which I really don’t want to!
— edit —
I didn’t realise in this that dirty attributes are maintained after the save of the model. So @page.attribute_was will still work after the yield in an around_save.
You could make the callback you want executed last an
around_savecallback. Check out the list of available callbacks and see if you can simply use a different callback “bucket” for some of your callbacks to ensure they are executed in the desired order.If you still end up with multiple
before_savecallbacks and need one to trigger last, you may want to create custom callbacks, like maybedefine_model_callbacks :split_save, registering your regularbefore_savecallbacks asbefore_split_savecallbacks, the one you want executed last as aafter_split_savecallback, and then just a singlebefore_savecallback that runs those two groups of callbacks (run_callbacks :split_save). SeeActiveModel::Callbacksfor more on how to do this.