Method: Blueprinter::Base.association

Defined in:
lib/blueprinter/base.rb

.association(method, options = {}) {|object, options| ... } ⇒ Field

Specify an associated object to be included for serialization. Takes a required method and an option.

Examples:

Specifying an association

class UserBlueprint < Blueprinter::Base
  # code
  association :vehicles, view: :extended, blueprint: VehiclesBlueprint
  # code
end

Passing a block to be evaluated as the value.

class UserBlueprint < Blueprinter::Base
  association :vehicles, blueprint: VehiclesBlueprint do |user, opts|
    user.vehicles + opts[:additional_vehicles]
  end
end

Parameters:

  • method (Symbol)

    the association name

  • options (Hash) (defaults to: {})

    options to overide defaults.

Options Hash (options):

  • :blueprint (Symbol)

    Required. Use this to specify the blueprint to use for the associated object.

  • :name (Symbol)

    Use this to rename the association in the JSON output.

  • :view (Symbol)

    Specify the view to use or fall back to to the :default view.

Yields:

  • (object, options)

    The object and the options passed to render are also yielded to the block.

Returns:

  • (Field)

    A Field object

Raises:



155
156
157
158
159
160
161
162
163
# File 'lib/blueprinter/base.rb', line 155

def self.association(method, options = {}, &block)
  raise BlueprinterError, 'blueprint required' unless options[:blueprint]

  field(
    method,
    options.merge(association: true, extractor: AssociationExtractor.new),
    &block
  )
end