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

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

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.curry(name: 'Jane')

create_tasks = rom.command(:tasks).create
  .curry [{ 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



93
94
95
96
97
98
99
100
# File 'lib/rom/sql/plugin/associates.rb', line 93

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) ⇒ Object

See Also:

  • Command::ClassInterface.build


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rom/sql/plugin/associates.rb', line 53

def build(relation, **options)
  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

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

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