Method: ROM::SQL::Relation::Reading#union

Defined in:
lib/rom/sql/relation/reading.rb

#union(relation, options = EMPTY_HASH) ⇒ Object

Adds a UNION clause for relation dataset using second relation dataset

@returRelation]

Examples:

users.where(id: 1).union(users.where(id: 2))
# => [{ id: 1, name: 'Piotr' }, { id: 2, name: 'Jane' }]

Parameters:

  • relation (Relation)

    Another relation

  • options (Hash) (defaults to: EMPTY_HASH)

    Options for union

Options Hash (options):

  • :alias (Symbol)

    Use the given value as the #from_self alias

  • :all (true, false)

    Set to true to use UNION ALL instead of UNION, so duplicate rows can occur

  • :from_self (true, false)

    Set to false to not wrap the returned dataset in a #from_self, use with care.



828
829
830
831
832
833
834
835
836
837
838
839
# File 'lib/rom/sql/relation/reading.rb', line 828

def union(relation, options = EMPTY_HASH, &)
  # We use the original relation name here if both relations have the
  # same name. This makes it so if the user at some point references
  # the relation directly by name later on things won't break in
  # confusing ways.
  same_relation = name == relation.name
  alias_name =  same_relation ? name : "#{name.to_sym}__#{relation.name.to_sym}"
  opts = { alias: alias_name.to_sym, **options }

  new_schema = schema.qualified(opts[:alias])
  new_schema.(new(dataset.__send__(__method__, relation.dataset, opts, &)))
end