Class: Iry::Constraint::ForeignKey

Inherits:
Object
  • Object
show all
Defined in:
lib/iry/constraint/foreign_key.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keys, name:, error_key:, message: :required) ⇒ ForeignKey

Returns a new instance of ForeignKey.

Parameters:

  • keys (<Symbol>)

    array of keys to track the uniqueness constraint of

  • message (Symbol, String) (defaults to: :required)

    the validation error message

  • name (String)

    constraint name

  • error_key (Symbol)

    key to which the validation error will be applied to



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/iry/constraint/foreign_key.rb', line 35

def initialize(
  keys,
  name:,
  error_key:,
  message: :required
)
  @keys = keys
  @message = message
  @name = name
  @error_key = error_key
end

Instance Attribute Details

#error_keySymbol

Returns:

  • (Symbol)


29
30
31
# File 'lib/iry/constraint/foreign_key.rb', line 29

def error_key
  @error_key
end

#keys<Symbol>

Returns:

  • (<Symbol>)


23
24
25
# File 'lib/iry/constraint/foreign_key.rb', line 23

def keys
  @keys
end

#messageSymbol, String

Returns:

  • (Symbol, String)


25
26
27
# File 'lib/iry/constraint/foreign_key.rb', line 25

def message
  @message
end

#nameString

Returns:

  • (String)


27
28
29
# File 'lib/iry/constraint/foreign_key.rb', line 27

def name
  @name
end

Class Method Details

.infer_name(keys, table_name) ⇒ String

Infers the unique constraint name based on keys and table name

Parameters:

  • keys (<Symbol>)
  • table_name (String)

Returns:

  • (String)


8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/iry/constraint/foreign_key.rb', line 8

def self.infer_name(keys, table_name)
  if keys.size > 1
    # PostgreSQL convention:
    return "#{table_name}_#{keys.join("_")}_fkey"
  end

  # Rails convention:
  column = keys.first
  id = "#{table_name}_#{column}_fk"
  hashed_id = OpenSSL::Digest::SHA256.hexdigest(id)[0..9]

  "fk_rails_#{hashed_id}"
end

Instance Method Details

#apply(model) ⇒ ActiveModel::Error

Parameters:

Returns:

  • (ActiveModel::Error)


49
50
51
# File 'lib/iry/constraint/foreign_key.rb', line 49

def apply(model)
  model.errors.add(error_key, message)
end