C
C
Cyril2020-04-22 23:19:34
MySQL
Cyril, 2020-04-22 23:19:34

How to cache raw SQL results in Rails?

There is a certain model MyModel , which describes a fairly large amount of data. For this model, a regular pure SQL query was written, which could not be written in the ActiveRecord version.

There was a need to use the cache in order not to constantly execute this request, but to store the values ​​in the cache for some time.

Let's say there is a code:

sql_query = " ... " #большущий запрос
items = Rails.cache.fetch("some_key", :expires_in => 1.day) do
    MyModel.connection.select_rows(sql_query)
end

puts items


When I execute a request, there is no difference, either I execute it without caching, or with caching. With the above construction, the request to the server is still executed.

How to make a pure SQL query and cache the result? Share your experience, please. Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question