diff options
author | Ryuta Kamizono <kamipo@gmail.com> | 2017-12-30 18:27:09 +0900 |
---|---|---|
committer | Ryuta Kamizono <kamipo@gmail.com> | 2017-12-30 18:27:09 +0900 |
commit | 7fae88f71d7ac0a0c0755ff5172fbde00c8a3248 (patch) | |
tree | 7ff1128423a2bd16df40bf6f7b2af49cbefe7e6c | |
parent | 11c06d3cbf17bb6133108df4207440a545bdc052 (diff) | |
download | rails-7fae88f71d7ac0a0c0755ff5172fbde00c8a3248.tar.gz rails-7fae88f71d7ac0a0c0755ff5172fbde00c8a3248.tar.bz2 rails-7fae88f71d7ac0a0c0755ff5172fbde00c8a3248.zip |
Fix `cache_key` with a relation having distinct and order
We can't replace existing SELECT list as long as having DISTINCT, it
will cause incorrect result.
And also, PostgreSQL has a limitation that ORDER BY expressions must
appear in select list for SELECT DISTINCT.
Therefore, we should not replace existing SELECT list when using
DISTINCT.
Fixes #29779.
-rw-r--r-- | activerecord/lib/active_record/collection_cache_key.rb | 4 | ||||
-rw-r--r-- | activerecord/test/cases/collection_cache_key_test.rb | 6 |
2 files changed, 8 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/collection_cache_key.rb b/activerecord/lib/active_record/collection_cache_key.rb index 12e4fae865..0520591f4f 100644 --- a/activerecord/lib/active_record/collection_cache_key.rb +++ b/activerecord/lib/active_record/collection_cache_key.rb @@ -6,8 +6,8 @@ module ActiveRecord query_signature = ActiveSupport::Digest.hexdigest(collection.to_sql) key = "#{collection.model_name.cache_key}/query-#{query_signature}" - if collection.loaded? - size = collection.size + if collection.loaded? || collection.distinct_value + size = collection.records.size if size > 0 timestamp = collection.max_by(×tamp_column)._read_attribute(timestamp_column) end diff --git a/activerecord/test/cases/collection_cache_key_test.rb b/activerecord/test/cases/collection_cache_key_test.rb index c3af32394e..cfe95b2360 100644 --- a/activerecord/test/cases/collection_cache_key_test.rb +++ b/activerecord/test/cases/collection_cache_key_test.rb @@ -142,6 +142,12 @@ module ActiveRecord assert_match(/\Adevelopers\/query-(\h+)-(\d+)-(\d+)\z/, developers.cache_key) end + test "cache_key with a relation having distinct and order" do + developers = Developer.distinct.order(:salary).limit(5) + + assert_match(/\Adevelopers\/query-(\h+)-(\d+)-(\d+)\z/, developers.cache_key) + end + test "cache_key with a relation having custom select and order" do developers = Developer.select("name AS dev_name").order("dev_name DESC").limit(5) |