The Spaghetti Refactory Established 2015

Touch objects in a has_and_belongs_to_many association

On has_many relations, there is a simple way to update all associated objects - just add touch: true and the updated_at field on all associated objects will get updated. This is a major issue with Russian Doll caching, because this is was expires the cache and makes sure the page shows the most recent changes. However has_and_belongs_to_many (HABTM) does not have a :touch option. It must be done manually. So, here's a quick and easy way to do this:

class Category
before_save :touch_videos

def touch_videos
videos.touch
end
end

class Video
def self.touch
update_all(updated_at: Time.now)
# or, if you need validations to run for some reason
find_each { |video| video.touch }
end
end

Tags