Module: AssociateJsonb::ConnectionAdapters::ReferenceDefinition

Defined in:
lib/associate_jsonb/connection_adapters/reference_definition.rb

Overview

:nodoc:

Constant Summary collapse

ForeignKeyDefinition =
ActiveRecord::ConnectionAdapters::ForeignKeyDefinition

Instance Method Summary collapse

Instance Method Details

#add_to(table) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/associate_jsonb/connection_adapters/reference_definition.rb', line 25

def add_to(table)
  return super unless store

  should_add_col = false
  if table.respond_to? :column_exists?
    should_add_col = !table.column_exists?(store)
  elsif table.respond_to? :columns
    should_add_col = table.columns.none? {|col| col.name.to_sym == store}
  end

  if should_add_col
    opts = { null: false, default: {} }
    table.column(store, :jsonb, **opts)
  end

  if foreign_key && column_names.length == 1
    fk = ForeignKeyDefinition.new(table.name, foreign_table_name, foreign_key_options)
    columns.each do |col_name, type, _|
      value = "        jsonb_foreign_key(\n          '\#{fk.to_table}',\n          '\#{fk.active_record_primary_key}',\n          \#{store},\n          '\#{col_name}',\n          '\#{type}'\n        )\n      SQL\n      table.constraint({\n        name: \"\#{table.name}_\#{col_name}_foreign_key\",\n        value: value\n      })\n    end\n  end\n\n  return unless index\n\n  columns.each do |col_name, type, opts|\n    type = :text if type == :string\n    table.index(\n      \"CAST (\\\"\#{store}\\\"->>'\#{col_name}' AS \#{type || :bigint})\",\n      using: :btree,\n      name: \"index_\#{table.name}_on_\#{store}_\#{col_name}\"\n    )\n\n    table.index(\n      \"(\\\"\#{store}\\\"->>'\#{col_name}')\",\n      using: :btree,\n      name: \"index_\#{table.name}_on_\#{store}_\#{col_name}_text\"\n    )\n  end\nend\n".squish

#column_nameObject

rubocop:enable Metrics/ParameterLists



21
22
23
# File 'lib/associate_jsonb/connection_adapters/reference_definition.rb', line 21

def column_name
  store_key || super
end

#initialize(name, store: false, store_key: false, **options) ⇒ Object

rubocop:disable Metrics/ParameterLists



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/associate_jsonb/connection_adapters/reference_definition.rb', line 8

def initialize(
  name,
  store: false,
  store_key: false,
  **options
)
  @store = store && store.to_sym
  @store_key = store_key && store_key.to_s unless options[:polymorphic]

  super(name, **options)
end