The after_find
callback is not being invoked by your where
call; it is being invoked by your destroy_all
call. destroy_all
will instantiate each UserProfile
object (and its associated objects) and call its destroy
method, one-by-one.
If you want to delete all the UserProfile
objects immediately, without instantiating them (and skipping all callbacks), then you can call:
UserProfile.where(user_id: user_id).delete_all
More information on the differences between destroy_all
and delete_all
can be found in other answers on StackOverflow, but the differences that you care about are:
- it will not instantiate the record
- it will not delete associated objects
- it will not invoke any callbacks
I would recommend that you not use after_find
the way you are using it. There are lots of ways to skip callbacks but almost nobody uses after_find
. (compared to after_create
, for example)
The options for skipping after_find
callbacks are limited. There are no built-in Rails methods for doing so. (except as described above) If you absolutely have to keep the callback, then your best bet is to add a conditional to the callback definition:
after_find :foo, if: -> { <some logic> }
If you use a conditional like that then you have to start thinking about how that variable is read and set in a multithreaded environment, and how do you handle concurrent requests without creating a race condition, and it sends you down an ugly path that is better handled by not using after_find
in the way you've described.