I have a model that is in a HABTM relationship with 2 other models:
Activity.rb
has_and_belongs_to_many :mandates, -> { distinct }
has_and_belongs_to_many :contacts, -> { distinct }
I had to add the following callbacks, since the models defined above have a 'score algorithm' that must be recomputed if activities are removed completely, or one is created initially:
after_commit :increase_contact_scores, :increase_mandate_scores
after_destroy :decrease_contact_scores, :decrease_mandate_scores
The callbacks code seems horribly the same. Is there a way to simplify this by somehow passing the HABT relation class from the callback to a more 'generic' method that can replace these?
I also need to figure out how to ONLY trigger the relevant callback based on the type of the HABTM (ie. not call both increases and both decreases, since if a mandate
is destroyed, calling the decrease_contacts_score
method will fail).
def increase_contact_scores
contacts.each do |contact|
if contact.activities.count == 1
contact.calculate_score
contact.save!
end
end
end
def increase_mandate_scores
mandates.each do |mandate|
if mandate.activities.count == 1
mandate.calculate_score
mandate.save!
end
end
end
def decrease_contact_scores
contacts.each do |contact|
if mandate.activities.count.zero?
contact.calculate_score
contact.save!
end
end
end
def decrease_mandate_scores
mandates.each do |mandate|
if mandate.activities.count.zero?
mandate.calculate_score
mandate.save!
end
end
end