Class: WebammToRails::Sources::Migrations::Associations

Inherits:
Object
  • Object
show all
Defined in:
lib/webamm_to_rails/sources/migrations/associations.rb

Instance Method Summary collapse

Constructor Details

#initialize(table_definition:, waml_definition:) ⇒ Associations

Returns a new instance of Associations.



5
6
7
8
# File 'lib/webamm_to_rails/sources/migrations/associations.rb', line 5

def initialize(table_definition:, waml_definition:)
  @table_definition = table_definition
  @waml_definition = waml_definition
end

Instance Method Details

#collectionObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/webamm_to_rails/sources/migrations/associations.rb', line 10

def collection
  base_associations = associations.map do |assoc|
    if assoc.type == 'belongs_to'
      relation_table_definition = find_table_definition(assoc.destination)
      assoc_def = "t.references :#{assoc.destination}, foreign_key: true, null: #{!assoc.required}"
      assoc_def += ", type: :uuid" if relation_table_definition.options&.use_uuid
      assoc_def
    elsif assoc.type == 'parent_children'
      assoc_def = "t.references :parent, foreign_key: { to_table: :#{@table_definition.table} }, null: true"
      assoc_def += ", type: :uuid" if @table_definition.options&.use_uuid
      assoc_def
    end
  end

  return base_associations unless @table_definition.options&.habtm

  habtm_tables = @table_definition.options.habtm_tables

  base_associations << "t.belongs_to :#{habtm_tables.first}"
  base_associations << "t.belongs_to :#{habtm_tables.second}"

  base_associations
end