📎 Webclip
To Serialize or Not to Serialize: ActiveModel Serializers
The post argues that raw Rails JSON is often too verbose for an Ember front end, especially when it includes fields like timestamps, full user objects, and full book records. ActiveModel Serializers is presented as the way to shape that response into the structure the client actually needs.
Reading notes#
- The example starts with a Rails app that returns a user’s wish lists as JSON for an Ember front end.
- The initial JSON includes more data than needed, such as created and updated timestamps, full user data, and full book data.
- The post says the front end only needs selected fields, such as
user_idandbook_ids. active_model_serializersis added to the Gemfile and installed with Bundler.- A serializer is generated for
WishList, along with anapplication_serializer. - The generated
WishListSerializerwhitelists attributes and recognizeshas_manyandbelongs_toassociations. - The first serialized response is grouped under a
wish_listskey. - The serializer is then adjusted to replace
belongs_to :userwith auser_idattribute. - A
BookSerializeris generated so books can be customized separately. - The post shows a private
booksmethod inWishListSerializerthat instantiatesBookSerializerfor each associated book. - Changing
BookSerializerchanges the book data returned through the wish list serializer. - The controller action does not need to change; Rails finds and uses the serializer automatically.
- The post notes that different serializers can be used for the same object type, including a more detailed book serializer when needed.
- It ends by pointing to documentation and related posts about serializers and caching.
