Method: Iry::Macros#foreign_key_constraint

Defined in:
lib/iry/macros.rb

#foreign_key_constraint(key_or_keys, name: nil, message: :required, error_key: nil) ⇒ void

This method returns an undefined value.

Tracks foreign key constraint for the given key (or keys) and convert constraint errors into validation errors

Parameters:

  • key_or_keys (Symbol, <Symbol>)

    key or array of keys to track the foreign key constraint of

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

    the validation error message

  • name (nil, String) (defaults to: nil)

    constraint name. If omitted, it will be inferred using table name + keys

  • error_key (nil, Symbol) (defaults to: nil)

    key to which the validation error will be applied to. If omitted, it will be applied to the first key

Raises:

  • (ArgumentError)

    raised if constraint name already in use by another constraint of any type



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/iry/macros.rb', line 66

def foreign_key_constraint(
  key_or_keys,
  name: nil,
  message: :required,
  error_key: nil
)
  keys = Array(key_or_keys)
  name ||= Constraint::ForeignKey.infer_name(keys, table_name)
  error_key ||= keys.first

  if constraints.key?(name)
    raise ArgumentError, "Constraint already exists"
  end

  self.constraints = constraints.dup
  constraints[name] = Constraint::ForeignKey.new(
    keys,
    message: message,
    name: name,
    error_key: error_key
  )
end