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.
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
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).
Most helpful comment
Less than ideal, but: