Ruby on Rails Saturday, June 17, 2017

I have the below code:

class ContactsController < ApplicationController
  # ..

  def top_3
    cache_identifiers = { contact_1: 1, contact_2: 2, contact_3: 3 }
    cache_keys = cache_identifiers.keys
    cached_keys_with_values = Rails.cache.read_multi(*cache_keys)
    uncached_keys = { |key| key unless cached_keys_with_values.has_key?(key) }.compact
    uncached_ids = { |key| cache_identifiers[key] }
    uncached_contacts = Contact.where(id: uncached_ids).to_a do |key, value|
      Rails.cache.write(key, value)

    @contacts = do |key|
      cached_keys_with_values[key] || uncached_contacts.shift

I am using memcached as cache store. Now my question is how can I invalidate the cache when say any of the attributes(name, email) of the contact record changes.

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment