rails-api/active_model_serializers — pull request #262 by seanabrahams (2013-03-31 18:39:20+00:00)
Title: Add test demonstrating serializable_hash cache bug.

When using caching, if an ArraySerializer generates the cache for an individual record subsequent calls to to_json for that record will not include sideloaded associations.

Let's dig in.

serializer.serializable_hash doesn't simply generate a hash, it has side effects. When sideloaded associations are involved it also populates @options[:hash] with the associations to sideload.

This means you can't simply cache serializable_hash when associations to be sideloaded are involved since serializable_hash does more than just return a hash.

When serialized_hash is cached before to_json, as is the case when an individual Serializer is used via an ArraySerializer, @options[:hash] doesn't get populated when you subsequently call serializer.to_json since this will use the cached serializable_hash which doesn't populate the @options[:hash] with the data to be sideloaded.

Digging deeper it's the include! method that populates @options[:hash] which is called via serializer.include_associations! which is called via serializer._serializable_hash.