AntonTkachov
AntonTkachov

Reputation: 1784

Callback after_[anything]

I've faced a situation, when I need to fire a callback for any event of the model. It's about cache reseting. I have Follow entity, where follower_id and following_id. If something happens with this entity (create/update/destroy and anything else that is possible) I need to reset some specific cache for both follower and following.

Right now I've finished with:

class Follow < ActiveRecord::Base
  after_save :reset_cache
  after_destroy :reset_cache

  def reset_cache
    ...
  end
end

Questions:

  1. Does this cover all possible cases which can happen with model object?
  2. Is there any one line approach to do this?

Thanks

Upvotes: 1

Views: 186

Answers (1)

theterminalguy
theterminalguy

Reputation: 1941

Here is a one line approach

class Follow < ActiveRecord::Base
  after_commit :reset_cache, on: [:update, :destroy]

  def reset_cache
  end 
end

See: http://guides.rubyonrails.org/active_record_callbacks.html

Upvotes: 2

Related Questions