Module: ROM::SQL::Plugin::Associates::ClassMethods Private

Defined in:
lib/rom/sql/plugin/associates.rb

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Instance Method Summary collapse

Instance Method Details

#associates(name, options = EMPTY_HASH) ⇒ Object

Set command to associate tuples with a parent tuple using provided keys

Examples:

class CreateTask < ROM::Commands::Create[:sql]
  relation :tasks
  associates :user, key: [:user_id, :id]
end

create_user = rom.command(:user).create.with(name: 'Jane')

create_tasks = rom.command(:tasks).create
  .with [{ title: 'One' }, { title: 'Two' } ]

command = create_user >> create_tasks
command.call

Parameters:

  • name (Symbol)

    The name of associated table

  • options (Hash) (defaults to: EMPTY_HASH)

    The options

Options Hash (options):

  • :key (Array)

    The association keys



112
113
114
115
116
117
118
119
# File 'lib/rom/sql/plugin/associates.rb', line 112

def associates(name, options = EMPTY_HASH)
  if associations.key?(name)
    raise ArgumentError,
          "#{name} association is already defined for #{self.class}"
  end

  associations(associations.merge(name => options))
end

#build(relation, options = EMPTY_HASH) ⇒ Object

See Also:

  • Command::ClassInterface.build


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rom/sql/plugin/associates.rb', line 70

def build(relation, options = EMPTY_HASH)
  command = super

  configured_assocs = command.configured_associations

  associate_options = command.associations.map { |(name, opts)|
    next if configured_assocs.include?(name)
    AssociateOptions.new(name, relation, opts)
  }.compact

  associate_options.each { |opts| opts.ensure_valid(self) }

  before_hooks = associate_options.reject(&:after?).map(&:to_hash)
  after_hooks = associate_options.select(&:after?).map(&:to_hash)

  command.
    with_opts(configured_associations: configured_assocs + associate_options.map(&:name)).
    before(*before_hooks).
    after(*after_hooks)
end