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 = cache_keys.map { |key| key unless cached_keys_with_values.has_key?(key) }.compact
    uncached_ids = uncached_keys.map { |key| cache_identifiers[key] }
    uncached_contacts = Contact.where(id: uncached_ids).to_a

    uncached_keys.zip(uncached_contacts).each do |key, value|
      Rails.cache.write(key, value)
    end

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

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 rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/13256849-6db8-47f9-97e8-c51688d54ba7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment