Problems with has_many: through, cache, touch and counter_cache

I have a lot of has_many: through relationships in my application. I am extensivley showing information related to this, for example, the number of connected objects. Whenever the user updates the relation, the connection table changes, and I can catch it with my sweepers.

The problem is that the connection table entries are deleted , not destroyed . If the relationship is gone, I have no way to find this, and I will show the misleading information from the cache. Everything like: touch => true, or: counter_cache => true works partially. It increases if relationships are updated or created. But if the user deletes the relationship, nothing happens .: counter_cache becomes broken: touch does not work.

The garbage solution should call .touch on the controller when the main model is saved. This kind of work, but it seems really unprofessional. This should be in the logic of the model, not in the controllers.

I feel like I'm missing something big, but I bow my head over it. Can anyone talk about this issue?

+4
source share
2 answers

Monkey Patch Active recording is not required. When defining your association, set :dependent to :destroy .

 class Book < ActiveRecord::Base has_many :authorships, :dependent => :destroy has_many :authors, :through => :authorships, :dependent => :destroy end 
+1
source

Check out the monkey patch Mark S. wrote to answer his own question: How do I create a complete audit trail in Rails for each table?

 ActiveRecord::Associations::HasManyThroughAssociation.class_eval do def delete_records(records) klass = @reflection.through_reflection.klass records.each do |associate| klass.destroy_all(construct_join_attributes(associate)) end end end 

This may be useful for your problem. Note that this was in Rails 2 .. things could be different if you are already using Rails 3.

0
source

All Articles