From 041b008d2425618c7f857635c9f48699213cfc90 Mon Sep 17 00:00:00 2001 From: Joseph Rodriguez Date: Wed, 29 Sep 2010 21:26:32 +1000 Subject: [PATCH] AR::Relation#cache_key gives a unique key for the relations query. This simplifies cache use for your relation objects --- activerecord/lib/active_record/relation.rb | 5 +++++ activerecord/test/cases/relations_test.rb | 11 +++++++++++ 2 files changed, 16 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 04ba5b2..72fa104 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/object/blank' +require 'digest/sha1' module ActiveRecord # = Active Record Relation @@ -296,6 +297,10 @@ module ActiveRecord def delete(id_or_array) where(@klass.primary_key => id_or_array).delete_all end + + def cache_key + "ar_relation/#{table.name}/#{Digest::SHA1.hexdigest(to_sql)}" + end def reload reset diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index d642aee..045e9c7 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -37,6 +37,17 @@ class RelationTest < ActiveRecord::TestCase assert x.klass.respond_to?(:find_by_id), '@klass should handle dynamic finders' end + def test_cache_key + assert_nothing_raised { Bird.scoped.cache_key } + + posts = Post.scoped + posts_by_author = posts.where('author_id = ?', 1) + + assert_not_equal posts.cache_key, posts_by_author.cache_key + assert_equal Post.where('author_id = ?', 1).cache_key, posts_by_author.cache_key + assert_not_equal posts_by_author.cache_key, posts_by_author.limit(2).cache_key + end + def test_multivalue_where posts = Post.where('author_id = ? AND id = ?', 1, 1) assert_equal 1, posts.to_a.size -- 1.7.0.3