Back to Guides

Associations

The general interface for associations is:

association_type ( association_name, options, &block )

association_type

Either has_one, has_many, belongs_to.

association_name

A method name the serializer calls.

options (Optional)

Can be:

  • key: Name used for the serialized association.
  • serializer:
  • if:
  • unless:
  • virtual_value:
&block (Optional)

A context that returns the association's attributes.

  • prevents association_name method from being called.
  • return value of block is used as the association value.
  • yields the serializer to the block.
  • include_data false prevents the data key from being rendered in the JSON API relationship.

::has_one

e.g.

has_one :bio
has_one :blog, key: :site
has_one :maker, virtual_value: { id: 1 }
has_one :blog do |serializer|
  serializer.cached_blog
end

def cached_blog
  cache_store.fetch("cached_blog:#{object.updated_at}") do
    Blog.find(object.blog_id)
  end
end

::has_many

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

::belongs_to

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

Polymorphic Relationships

Polymorphic relationships are serialized by specifying the relationship, like any other association. For example:

class PictureSerializer < ActiveModel::Serializer
  has_one :imageable
end

For more, see the tests for each adapter.

results matching ""

    No results matching ""