Configure root key and association name inference
mainWhen Alba.inflector is configured (e.g., to :active_support), Alba can automatically infer root keys and association resource names. To enable this, you must call root_key! in your resource class. This allows many associations to automatically find the correct resource class based on the association name and handles pluralization/singularization of the root key based on whether the input is a collection or a single object.
Alba.inflector = :active_support
class ArticleResource
include Alba::Resource
attributes :title
end
class UserResource
include Alba::Resource
root_key! # Required for inferred root key
attributes :id
many :articles
end
user = User.new(1)
user.articles << Article.new(1, 'The title')
# Single object results in singular root key
UserResource.new(user).serialize
# => '{"user":{"id":1,"articles":[{"title":"The title"}]}}'
# Collection results in plural root key
UserResource.new([user]).serialize
# => '{"users":[{"id":1,"articles":[{"title":"The title"}]}]}'