Repository is archived
No commit activity in last 3 years
No release in over 3 years
Make ActiveRecord queries cacheable throughout your apps!
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

< 5.0, >= 3.0
>= 0
>= 0

Runtime

< 5.0, >= 3.0
 Project Readme

Collection Cache Keys for ActiveRecord 3.0 - 4.2

Code Climate Build Status

This gem is a backport of Rails 5's Relation#cache_key feature, allowing smarter, deterministic caching of ActiveRecord relations.

Installation

Add activerecord-collection_cache_key to your Gemfile:

gem 'activerecord-collection_cache_key'

Usage

You can now access the key for any ActiveRecord collection via its #cache_key method:

@scope = MyModel.where(active: 1).cache_key

And then use it in your controller:

def index
  @scope = MyModel.where(active: 1)
  Rails.cache.fetch(@scope.cache_key) do
    respond_with(@scope)
  end
end

Notes on Rails 3.x and .all:

In some versions of Rails covered by this gem, Model.all returns an array, and not an instance of ActiveRecord::Relation. In these cases it's possible to access the default key via class method on the model:

MyModel.collection_cache_key

Contributing

See CONTRIBUTING.md for details

Changelog

See CHANGELOG.md for details