Module: ActiveRecord::JSONB::Associations::JoinDependency::JoinAssociation

Defined in:
lib/activerecord/jsonb/associations/join_dependency/join_association.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#build_constraint(klass, table, key, foreign_table, foreign_key) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/activerecord/jsonb/associations/join_dependency/join_association.rb', line 7

def build_constraint(klass, table, key, foreign_table, foreign_key)
  if reflection.options.key?(:foreign_store)
    build_eq_constraint(
      table, table[reflection.options[:foreign_store]],
      key, foreign_table, foreign_key
    )
  elsif reflection.options.key?(:store) && reflection.belongs_to?
    build_eq_constraint(
      foreign_table, foreign_table[reflection.options[:store]],
      foreign_key, table, key
    )
  elsif reflection.options.key?(:store) # && reflection.has_one?
    build_contains_constraint(
      table, table[reflection.options[:store]],
      key.pluralize, foreign_table, foreign_key
    )
  else
    super
  end
end

#build_contains_constraint(table, jsonb_column, key, foreign_table, foreign_key) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/activerecord/jsonb/associations/join_dependency/join_association.rb', line 39

def build_contains_constraint(
  table, jsonb_column, key, foreign_table, foreign_key
)
  Arel::Nodes::JSONBHashArrow.new(table, jsonb_column, key).contains(
    ::Arel::Nodes::SqlLiteral.new(
      "jsonb_build_array(#{foreign_table.name}.#{foreign_key})"
    )
  )
end

#build_eq_constraint(table, jsonb_column, key, foreign_table, foreign_key) ⇒ Object

rubocop:enable Metrics/AbcSize, Metrics/MethodLength



29
30
31
32
33
34
35
36
37
# File 'lib/activerecord/jsonb/associations/join_dependency/join_association.rb', line 29

def build_eq_constraint(
  table, jsonb_column, key, foreign_table, foreign_key
)
  Arel::Nodes::JSONBDashDoubleArrow.new(table, jsonb_column, key).eq(
    ::Arel::Nodes::SqlLiteral.new(
      "CAST(#{foreign_table.name}.#{foreign_key} AS text)"
    )
  )
end