Skip to content

Commit

Permalink
Do not silently fail to generate a cache_version
Browse files Browse the repository at this point in the history
When an `updated_at` column exists on the model, but is not available on the instance (likely due to a select), we should raise an error rather than silently not generating a cache_version. Without this behavior it's likely that cache entries will not be able to be invalidated and this will happen without notice. 

This behavior was reported and described by @lsylvester in #34197 (comment).
  • Loading branch information
schneems committed Oct 17, 2018
1 parent 0445483 commit 2f99da0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 11 additions & 6 deletions activerecord/lib/active_record/integration.rb
Expand Up @@ -97,13 +97,18 @@ def cache_key(*timestamp_names)
# +false+ (which it is by default until Rails 6.0).
def cache_version
return unless cache_versioning
return unless has_attribute?("updated_at")

timestamp = updated_at_before_type_cast
if can_use_fast_cache_version?(timestamp)
raw_timestamp_to_cache_version(timestamp)
elsif timestamp = updated_at
timestamp.utc.to_s(cache_timestamp_format)
if has_attribute?("updated_at")
timestamp = updated_at_before_type_cast
if can_use_fast_cache_version?(timestamp)
raw_timestamp_to_cache_version(timestamp)
elsif timestamp = updated_at
timestamp.utc.to_s(cache_timestamp_format)
end
else
if self.class.has_attribute?("updated_at")
raise ActiveModel::MissingAttributeError, "missing attribute: updated_at"
end
end
end

Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/cache_key_test.rb
Expand Up @@ -119,5 +119,13 @@ class CacheMeWithVersion < ActiveRecord::Base
record_from_db.cache_version
end
end

test "updated_at on class but not on instance raises an error" do
record = CacheMeWithVersion.create
record_from_db = CacheMeWithVersion.where(id: record.id).select(:id).first
assert_raises(ActiveModel::MissingAttributeError) do
record_from_db.cache_version
end
end
end
end

0 comments on commit 2f99da0

Please sign in to comment.