Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

A Backport of Rails 5's collection cache keys to AR 3 and 4

License

Notifications You must be signed in to change notification settings

customink/activerecord-collection_cache_key

Repository files navigation

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

About

A Backport of Rails 5's collection cache keys to AR 3 and 4

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages