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



161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/blueprinter/base.rb', line 161

def self.association(method, options = {}, &block)
  validate_blueprint!(options[:blueprint], method)

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