Class: DynamicActiveModel::ForeignKeyConstraints

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

Overview

Reads the database's foreign key constraints and resolves them to models, so Associations can relate columns that don't follow the

_id naming convention (posts.author_id => users) and self-references (employees.manager_id).

Skipped: composite constraints, columns without the id suffix (a belongs_to named after the column itself would hide it), and constraints whose table or referenced table has no model.

Examples:

constraints = DynamicActiveModel::ForeignKeyConstraints.new(database)
constraints.find(DB::Post, 'author_id') # => #<struct referenced_model=DB::User, ...>

Defined Under Namespace

Classes: Constraint

Instance Method Summary collapse

Constructor Details

#initialize(database) ⇒ ForeignKeyConstraints

Returns a new instance of ForeignKeyConstraints.

Parameters:

  • database (Database) —

    The database whose models' constraints to read



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

def initialize(database)
  @database = database
  @constraints = database.models.flat_map { |model| constraints_for(model) }
                         .to_h { |constraint| [[constraint.model, constraint.column], constraint] }
end

Instance Method Details

#find(model, column) ⇒ Constraint?

Returns The column's constraint, if it has one.

Parameters:

  • model (Class) —

    The model with the column

  • column (String) —

    The column name

Returns:

  • (Constraint, nil) —

    The column's constraint, if it has one



29
30
31
# File 'lib/dynamic-active-model/foreign_key_constraints.rb', line 29

def find(model, column)
  @constraints[[model, column]]
end

#size ⇒ Integer

Returns Number of usable constraints.

Returns:

  • (Integer) —

    Number of usable constraints



34
35
36
# File 'lib/dynamic-active-model/foreign_key_constraints.rb', line 34

def size
  @constraints.size
end