Does ActiveRecord cache query results?
- Jun 6, 2017
- 1 min read
So I was building a basic CRUD app for the command line. It allows the user to create, read, update, and delete reviews for restaurants in the CLI. It uses ActiveRecord and SQLite as its database engine.
There was a curious thing happening.
Consider this example (also see screencast):
1./ Read the data > showing 2 records
2./ Add 1 additional record.
3./ Read the data > showing 2 records. Where is the 3rd one?
4./ Exit and re-open the app.
5./ Read the data > showing 3 records.
What is happening? Is ActiveRecord querying the database once and putting the results in a local memory space for the duration of the session? Yes, it does!
A google search for "ActiveRecord query cache" took me to the AR API Doc.
"Attributes are reloaded from the database, and caches busted, in particular the associations cache and the QueryCache."
Added it into the executable file...
... and works like a charm!
Note: There is another method to clear the cache called #reset. The difference is that the cache is cleared but the database is not queried again.





Comments