In my Rails app, I have some after_commit
... on: :update
callbacks that are responsible for doing some work after a user updates their account settings.
Trouble is that these callbacks get triggered when a user logs out. I checked to see what's being updated on the user by calling self.previous_changes
, and here's the output:
=> {"remember_created_at"=>[Wed, 06 May 2020 20:32:09 UTC +00:00, nil], "updated_at"=>[Thu, 07 May 2020 14:52:42 UTC +00:00, Thu, 07 May 2020 14:54:40 UTC +00:00]}
So as you can see a logout clears "remember_created_at"
and updates "updated_at"
.
I could make a method on the user called is_logging_out?
that checks for these two changed attributes and returns true, but that feels hack-y and I was wondering if there's a more elegant way to do this.
(In case it matters I'm on devise v3.5.10)
Model callbacks have this drawback. I strongly promote not using model callbacks in favour of Decorators or explicit invokation.
However, if you are sure you need this callback, then why not try skipping the callback unless remember_created_at
is not nil?
def your_callback_method
return unless remember_created_at
#do stuff
end
You could either skip it in the callback method itself or add if: -> { record.remember_created_at }
to the after_commit
declaration
Please do not add a method called is_logging_out?
in the model because this is not model responsibility. The model should not depend on what the user ongoing action is.