Is it possible to cache custom sql queries in Rails?

前端 未结 2 2306
慢半拍i
慢半拍i 2021-02-20 04:28

In the home_controller of my Rails 4 app, I perform a custom sql query and save the results to an instance variable

@studentscoring = ActiveRecord::Base.connecti         


        
2条回答
  •  孤街浪徒
    2021-02-20 05:17

    Cache the query results in your controller. You can read or write back to the cache in one call (that is, set the data in the cache if it does not already exist)

    def index
      @studentscoring = Rails.cache.fetch("your_cache_key", :expires_in => 5.minutes) do
        ActiveRecord::Base.connection.select_rows(sql_string_student)
      end
    end
    

    So the above will first check the cache for "your_cache_key" and if the data exists will return it from the cache. If it does not exist than the block will execute and it will be set in the cache

提交回复
热议问题