ruby-on-rails-4associations

rails touch chain with has_many :through associations


Using a join model, with a has_many :through on this example setup

class Collage
 has_many :arrangements
 has_many :photos, through: :arrangements

class Photo
 has_many :arragements
 has_many :collages, through: :arragements
end

class Arragement
belongs_to :photo
belongs_to _collage
end

The photo may change it size, which will cause the collage to change

Using the touch: true, doesn't work this way, because the chain isn't "one way up", as arragement points to Photo and Collage

How can I work this so a Photo change (ie touch) would also touch its Collages?


Solution

  • Here's an even shorter version:

    class Photo
      has_many :arragements
      has_many :collages, through: :arragements
    
      after_save { collages.find_each(&:touch) }
    end