I have 2 Rails models: a book and a category, where the book belongs_to category, the has_many category.
The category name is displayed on each page of the book, and the pages are cached.
If I changed the name of the category (say, from “Sci Fi” to “Science Fiction”), then all the relevant pages of the book will be outdated, and the books need to be “touched” to cause HTML regeneration.
It would seem to make sense to do:
class Category << ActiveRecord::Base has_many :books, touch: true end
But the option is not available , I think, because the touch mechanism will instantiate each object, which can lead to a serious performance hit for has_many .
To avoid this, I use raw SQL as follows:
class Category << ActiveRecord::Base has_many :books after_update -> { ActiveRecord::Base.connection.execute "UPDATE books SET updated_at='#{current_time_string}' WHERE category_id=#{id})" } end
This is pretty awful. Is there a better way?
source share