'Rails override updated_at with another column to get correct cache_key

Am using Rails 3.2.13. We use last_modified_time as our last updated column. My problem is that when i do model.cache_key it does not take into account the :last_modifed_time column.

Current (Rails 3.2.13) implementation in Rails:

# Returns a cache key that can be used to identify this record.
#
# ==== Examples
#
#   Product.new.cache_key     # => "products/new"
#   Product.find(5).cache_key # => "products/5" (updated_at not available)
#   Person.find(5).cache_key  # => "people/5-20071224150000" (updated_at available)
def cache_key
  debugger
  case
  when new_record?
    "#{self.class.model_name.cache_key}/new"
  when timestamp = self[:updated_at]
    timestamp = timestamp.utc.to_s(cache_timestamp_format)
    "#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
  else
    "#{self.class.model_name.cache_key}/#{id}"
  end
end

Am overriding it in my model like this:

def cache_key
  updated_at = self[:updated_at]

  if self.last_modified_time && !updated_at
    timestamp = self.last_modified_time.utc.to_s(cache_timestamp_format)
    "#{super}-#{timestamp}"
  end
end

My question is: is there a simpler way to override the :updated_at to get the correct cache_key ?



Solution 1:[1]

I just ran into this same problem. This isn't necessarily simpler, but if you were planning to upgrade to Rails 4 anyway, you can simply override this method in your model:

private
  def timestamp_attributes_for_update
    super << :last_modifed_time
  end

Unfortunately, as you discovered, since Rails 3 hardcodes the :updated_at value in cache_key, this solution doesn't work. However, this is fixed in Rails 4.

Solution 2:[2]

In rails 5, timestamp_attributes_for_update is class method and only accepts string instead of symbol, so you could do this in model:

private

  def self.timestamp_attributes_for_update
    super << "last_modified_time" # must be string
  end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dgross
Solution 2