How to cache a query in Ruby on Rails 3

后端 未结 2 1759
一生所求
一生所求 2021-02-03 12:37

I have the following query in my application

@categories = Category.joins(:posts).select(\'distinct categories.*\').order(\'label\')

This query

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 12:59

    In your controller, you can try something like:

    @categories = Rails.cache.fetch('categories', :expires_in => 24.hours) { Category.joins(:posts).select('distinct categories.*').order('label') }
    

    Which will only read to see if the following data block 'categories' has been cached and not expired. If expired after 24 hours, will then query the model and write the new record into Rails cache.

    For more information, I followed the following guide.

    Try it out. I have it working this way. Hope that helps.

提交回复
热议问题