Caching associations in active model serializers

StackOverflow https://stackoverflow.com/questions/20894970
  •  
  •  | 
  •   ( words)
 Checked

Question

Currently, I have the following serializers:

class UserSerializer < ActiveModel::Serializer
  cached
  delegate :cache_key, to: :object
  has_many :profiles
end

class ProfileSerializer < ActiveModel::Serializer
  cached
  delegate :cache_key, to: :object
  has_many :pages
end

class PageSerializer < ActiveModel::Serializer
  cached
  delegate :cache_key, to: :object
  has_many :posts
end

For various reasons, I need to serialize all of the associated profiles, pages, and posts when serializing my User model. Unfortunately, this results in a rather large JSON hash that is difficult to cache efficiently - my local memcached server can store only around 75 serialized users. Is there a way to set up the serializers so that instead of caching the output of the entire user model JSON, I only cache the unique parts of the JSON and commit another cache fetch to retrieve the serialized data for the associated profiles, pages, and posts?

No correct solution

OTHER TIPS

I don't think there's a way to do that within ActiveModel::Serializers. You could reduce the cache size at the cost of complicating your code. Something like this would work:

user_json = UserSerializer.new(@user).as_json
user_json[:profiles] = @user.profiles.map { |profile| ProfileSerializer.new(profile).as_json }
etc.

In your example, there would of course be more nesting required.

This isn't a great solution - if you're bound to returning deeply nested JSON, I think the best short-term option would be to add some more memcache capacity. Long-term it might be worth rethinking this approach, as it might not be sustainable to return everything at once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow