Given a serializer class:
class SomeSerializer < ActiveModel::Serializer
end
The following methods may be defined in it:
Serialization of the resource title
and body
In Serializer | #attributes |
---|---|
attributes :title, :body |
{ title: 'Some Title', body: 'Some Body' } |
attributes :title, :body def body "Special #{object.body}" end |
{ title: 'Some Title', body: 'Special Some Body' } |
Serialization of the resource title
In Serializer | #attributes |
---|---|
attribute :title |
{ title: 'Some Title' } |
attribute :title, key: :name |
{ name: 'Some Title' } |
attribute :title { 'A Different Title'} |
{ title: 'A Different Title' } |
attribute :title def title 'A Different Title' end |
{ title: 'A Different Title' } |
e.g.
has_one :bio
has_one :blog, key: :site
has_one :maker, virtual_value: { id: 1 }
e.g.
has_many :comments
has_many :comments, key: :reviews
has_many :comments, serializer: CommentPreviewSerializer
has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]
has_many :comments, key: :last_comments do
last(1)
end
e.g.
belongs_to :author, serializer: AuthorPreviewSerializer
belongs_to :author, key: :writer
belongs_to :post
belongs_to :blog
def blog
Blog.new(id: 999, name: 'Custom blog')
end
e.g.
cache key: 'post', expires_in: 0.1, skip_digest: true
cache expires_in: 1.day, skip_digest: true
cache key: 'writer', skip_digest: true
cache only: [:name], skip_digest: true
cache except: [:content], skip_digest: true
cache key: 'blog'
cache only: [:id]
e.g.
# Uses a custom non-time-based cache key
def cache_key
"#{self.class.name.downcase}/#{self.id}"
end
e.g.
class UserProfileSerializer < ActiveModel::Serializer
type 'profile'
end
e.g.
link :other, 'https://example.com/resource'
link :self do
href "https://example.com/link_author/#{object.id}"
end
The object being serialized.
PR please :)
PR please :)
The serialized value for a given key. e.g. read_attribute_for_serialization(:title) #=> 'Hello World'
PR please :)
PR please :)
Given two models, a Post(title: string, body: text)
and a
Comment(name: string, body: text, post_id: integer)
, you will have two
serializers:
class PostSerializer < ActiveModel::Serializer
cache key: 'posts', expires_in: 3.hours
attributes :title, :body
has_many :comments
end
and
class CommentSerializer < ActiveModel::Serializer
attributes :name, :body
belongs_to :post
end
Generally speaking, you, as a user of ActiveModelSerializers, will write (or generate) these serializer classes.
For more information, see the Serializer class on GitHub
If you want to override any association, you can use:
class PostSerializer < ActiveModel::Serializer
attributes :id, :body
has_many :comments
def comments
object.comments.active
end
end
If you want to override any attribute, you can use:
class PostSerializer < ActiveModel::Serializer
attributes :id, :body
has_many :comments
def body
object.body.downcase
end
end