aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation.rb
diff options
context:
space:
mode:
authorAlberto F. Capel <afcapel@gmail.com>2015-07-14 23:47:16 +0100
committerAlberto F. Capel <afcapel@gmail.com>2015-07-20 01:46:03 +0100
commit476e3f552f59d208cb284f509760b44ad780c17a (patch)
tree900866eb6f02b5a5231f53db9dd5c37c03527852 /activerecord/lib/active_record/relation.rb
parent6ffec3c16c0ee0b0ab4643907af1f2ed80a71a9a (diff)
downloadrails-476e3f552f59d208cb284f509760b44ad780c17a.tar.gz
rails-476e3f552f59d208cb284f509760b44ad780c17a.tar.bz2
rails-476e3f552f59d208cb284f509760b44ad780c17a.zip
Add #cache_key to ActiveRecord::Relation.
Diffstat (limited to 'activerecord/lib/active_record/relation.rb')
-rw-r--r--activerecord/lib/active_record/relation.rb26
1 files changed, 26 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index e4df122af6..3ed04dee3b 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -298,6 +298,32 @@ module ActiveRecord
limit_value ? to_a.many? : size > 1
end
+ # Returns a cache key that can be used to identify the records fetched by
+ # this query. The cache key is built with a fingerprint of the sql query,
+ # the number of records matched by the query and a timestamp of the last
+ # updated record. When a new record comes to match the query, or any of
+ # the existing records is updated or deleted, the cache key changes.
+ #
+ # Product.where("name like ?", "%Cosmic Encounter%").cache_key
+ # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000"
+ #
+ # If the collection is loaded, the method will iterate through the records
+ # to generate the timestamp, otherwise it will trigger one SQL query like:
+ #
+ # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%')
+ #
+ # You can also pass a custom timestamp column to fetch the timestamp of the
+ # last updated record.
+ #
+ # Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at)
+ #
+ # You can customize the strategy to generate the key on a per model basis
+ # overriding ActiveRecord::Base#collection_cache_key.
+ def cache_key(timestamp_column = :updated_at)
+ @cache_keys ||= {}
+ @cache_keys[timestamp_column] ||= @klass.collection_cache_key(self, timestamp_column)
+ end
+
# Scope all queries to the current scope.
#
# Comment.where(post_id: 1).scoping do