Class: DynamicActiveModel::Associations

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic-active-model/associations.rb

Overview

The Associations class is responsible for automatically detecting and setting up ActiveRecord relationships between models based on database schema analysis. It supports the following relationship types:

  • belongs_to
  • has_many
  • has_one (automatically detected from unique constraints)
  • has_and_belongs_to_many (automatically detected from join tables)

Examples:

Basic Usage

db = DynamicActiveModel::Database.new(DB, database_config)
db.create_models!
associations = DynamicActiveModel::Associations.new(db)
associations.build!

Custom Foreign Key

associations.add_foreign_key('users', 'manager_id', 'manager')

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(database) ⇒ Associations

Initializes a new Associations instance

Parameters:

  • database (Database) —

    The database instance containing the models



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dynamic-active-model/associations.rb', line 32

def initialize(database)
  @database = database
  @table_indexes = {}
  @join_tables = []
  @foreign_keys = {}
  database.models.each do |model|
    @foreign_keys[model.table_name] = ForeignKey.new(model)
    # through the schema cache, so a Rails schema cache dump spares one query per table
    @table_indexes[model.table_name] = model.connection.schema_cache.indexes(model.table_name)
    @join_tables << model if join_table?(model)
  end
end

Instance Attribute Details

#database ⇒ Database (readonly)

Returns The database instance containing the models.

Returns:

  • (Database) —

    The database instance containing the models



22
23
24
# File 'lib/dynamic-active-model/associations.rb', line 22

def database
  @database
end

#join_tables ⇒ Array (readonly)

Returns List of detected join tables.

Returns:

  • (Array) —

    List of detected join tables



28
29
30
# File 'lib/dynamic-active-model/associations.rb', line 28

def join_tables
  @join_tables
end

#table_indexes ⇒ Hash (readonly)

Returns Mapping of table names to their indexes.

Returns:

  • (Hash) —

    Mapping of table names to their indexes



25
26
27
# File 'lib/dynamic-active-model/associations.rb', line 25

def table_indexes
  @table_indexes
end

Instance Method Details

#add_foreign_key(table_name, foreign_key, relationship_name = nil) ⇒ Object

Adds a custom foreign key relationship

Parameters:

  • table_name (String) —

    Name of the table with the foreign key

  • foreign_key (String) —

    Name of the foreign key column

  • relationship_name (String, nil) (defaults to: nil) —

    Custom name for the relationship

Raises:



50
51
52
53
54
# File 'lib/dynamic-active-model/associations.rb', line 50

def add_foreign_key(table_name, foreign_key, relationship_name = nil)
  @foreign_keys
    .fetch(table_name.to_s) { raise ModelNotFound, "no model found for table #{table_name}" }
    .add(foreign_key, relationship_name)
end

#build! ⇒ void

This method returns an undefined value.

Builds all relationships between models based on foreign keys and constraints This method:

  1. Maps foreign keys to their corresponding models
  2. Adds belongs_to relationships
  3. Adds has_many or has_one relationships based on unique constraints
  4. Sets up has_and_belongs_to_many relationships for join tables


84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/dynamic-active-model/associations.rb', line 84

def build!
  foreign_key_to_models = create_foreign_key_to_model_map

  @database.models.each do |model|
    model.column_names.each { |column_name| add_column_relationships(model, column_name, foreign_key_to_models) }
  end

  @join_tables.each do |join_table_model|
    models = join_table_model.column_names.map do |column_name|
      foreign_key_to_models.dig(column_name.downcase, 0, 0)
    end.compact
    add_has_and_belongs_to_many(join_table_model, models) if models.size == 2
  end

  HasManyThrough.new(@database.models, table_indexes).build! if @has_many_through
end

#use_foreign_key_constraints! ⇒ void

This method returns an undefined value.

Relates columns through the database's foreign key constraints as well as by naming convention. A column with a constraint follows the constraint.



59
60
61
# File 'lib/dynamic-active-model/associations.rb', line 59

def use_foreign_key_constraints!
  @constraints = ForeignKeyConstraints.new(@database)
end

#use_has_many_through! ⇒ void

This method returns an undefined value.

Also adds has_many :through associations across join models (see HasManyThrough)



65
66
67
# File 'lib/dynamic-active-model/associations.rb', line 65

def use_has_many_through!
  @has_many_through = true
end

#use_optional_belongs_to! ⇒ void

This method returns an undefined value.

Makes every belongs_to optional, including those on NOT NULL foreign keys, so saving a record doesn't validate that its parent exists (or query for it). For tools that write rows whose parents may be missing, such as data repair scripts.



73
74
75
# File 'lib/dynamic-active-model/associations.rb', line 73

def use_optional_belongs_to!
  @optional_belongs_to = true
end