Active_model_serializers: Caching entire collection

Created on 3 Jul 2016  路  4Comments  路  Source: rails-api/active_model_serializers

I understand that AMS caches objects individually. And it seems to work great. Here is my serializer -

class ViewerSerializer < ActiveModel::Serializer
  cache key: 'viewer'
  attributes :id, :name, :email, :code, :has_name,
             :updated_at, :uuid, :has_signed_in,
             :chat_channel, :custom_data
end

And this is my controller action -

def index
    event = Event.friendly.find(params[:event_id])
    render json: event.viewers, each_serializer: ViewerSerializer
  end

Although individual viewer objects are being fetched from the cache, the query to fetch all the viewers is still firing - and I understand why that's happening.

Inorder to prevent even that from hiring, should I have a serializer that has viewers as an attribute (returning all the viewers of the event) and the cache_key as one of viewer_count or latest_updated_at or something like that?

Is that the recommended approach? I am wondering if something like this can be done without introducing an additional serializer.

Environment

ActiveModelSerializers Version: 0.10.1
Ruby: ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
OS Type & Version: Ubuntu 14.10
Integrated application and version: Rails 4.2.6

C Caching

Most helpful comment

Less than ideal, but:

json = Rails.cache.fetch(your_cache_key) do
  render_to_string json: event.viewers, each_serializer: ViewerSerializer
end

render json: json

All 4 comments

Less than ideal, but:

json = Rails.cache.fetch(your_cache_key) do
  render_to_string json: event.viewers, each_serializer: ViewerSerializer
end

render json: json

@rzane that's a good idea. Thanks.

@rzane great!

@bf4 do you have plans for this PR? Otherwise I would prefer to close this as the code @rzane shared above is good enough for the purpose (we are also using the same technique in production).

Was this page helpful?
0 / 5 - 0 ratings