Here is my code in ProductCategory model:
has_many :products def products_count Rails.cache.fetch([cache_key, __method__]) do products.count end end
In Product model:
belongs_to :product_category, touch: true
Once I create a new product I can see from the log the updated_at field being updated:
ProductCategory Update (2.6ms) UPDATE "product_categories" SET"updated_at" = $1 WHERE "product_categories"."id" = $2[["updated_at", "2021-08-04 15:34:55.520408"], ["id", 7]] (1.7ms)COMMIT
Still:
ProductCategory.find(7).products_count // returns 0ProductCategory.find(7).products.count // returns 1
If I execute Rails.cache.clear the results match so I guess Redis not regenerating cache after touch?