Method: Blueprinter::Base.association

Defined in:
lib/blueprinter/base.rb

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

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:

Raises:



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

def association(method, options = {}, &block)
  raise ArgumentError, ':blueprint must be provided when defining an association' unless options[:blueprint]

  method = method.to_sym
  current_view << Association.new(
    method:,
    name: options.fetch(:name) { method },
    extractor: options.fetch(:extractor) { AssociationExtractor.new },
    blueprint: options.fetch(:blueprint),
    parent_blueprint: self,
    view: options.fetch(:view, :default),
    options: options.except(:name, :extractor, :blueprint, :view).merge(block:)
  )
end