Skip to content

Add improved cache hits for ActiveRecord::Relation collections#25

Open
quorak wants to merge 5 commits intoyonahforst:masterfrom
quorak:master
Open

Add improved cache hits for ActiveRecord::Relation collections#25
quorak wants to merge 5 commits intoyonahforst:masterfrom
quorak:master

Conversation

@quorak
Copy link
Copy Markdown

@quorak quorak commented Mar 20, 2021

Sometimes queries can be very complex and populating models from queries with many includes take
up the majority of time. After checking the cache, it is than obvious populating all these models was not
necessary as we have a hit. Why not checking the cache with a simple query to build the cache-key
and only fire the complex query for those models, that do not exist in the cache?

For these cases you can paste the ActiveRecord::Relation and cache_collection! will:

  1. unscope all includes for the initial query to build all cache_key's (make sure you use joins for
    statements that are use in where)

  2. gets the result from cache with Rails.cache.read_multi for existing cache_key hits

  3. gets all missed hits from the database with complex includes and all fields

  4. builds the block with all data

  5. uses Rails.cache.write_multi if available to populate the cache with the missed values

    json.cache_collection! Post.includes(:author) do |post|
    json.partial! 'post', :post => post
    end

quorak and others added 5 commits November 4, 2020 06:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant