top of page

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


You Might Also Like:
IMG_20170609_201523
Screen Shot 2017-06-06 at 4.06.27 PM
Screen Shot 2017-06-11 at 11.45.13 AM
IMG_1521
IMG_20170518_185655
IMG_20170519_173940
IMG_20170515_164604
IMG_20170518_183205
IMG_20170518_183126
IMG_20170518_183254
IMG_20170503_153032
IMG_20170518_182930
IMG_20170519_074026
flatiron-school-51
IMG_20170518_183215
Hi,

I am Quynh. Recently, I took an exciting decision: I want to become a software developer.

Follow me on my journey! It starts at a coding bootcamp in New York...

 

Read More

 

bottom of page