This gem is a backport of Rails 5's Relation#cache_key
feature,
allowing smarter, deterministic caching of ActiveRecord relations.
Add activerecord-collection_cache_key
to your Gemfile
:
gem 'activerecord-collection_cache_key'
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
See CONTRIBUTING.md for details
See CHANGELOG.md for details