Class: DatabaseValidations::BelongsToOptions

Inherits:
Object
  • Object
show all
Defined in:
lib/database_validations/lib/db_belongs_to/belongs_to_options.rb

Constant Summary collapse

VALIDATOR_MESSAGE =
if ActiveRecord::VERSION::MAJOR < 5
  :blank
else
  :required
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column, relation, adapter) ⇒ BelongsToOptions

Returns a new instance of BelongsToOptions.



16
17
18
19
20
21
22
23
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 16

def initialize(column, relation, adapter)
  @column = column
  @relation = relation
  @adapter = adapter

  raise_if_unsupported_database!
  raise_if_foreign_key_missed! unless ENV['SKIP_DB_UNIQUENESS_VALIDATOR_INDEX_CHECK']
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



14
15
16
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 14

def adapter
  @adapter
end

#columnObject (readonly)

Returns the value of attribute column.



14
15
16
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 14

def column
  @column
end

#relationObject (readonly)

Returns the value of attribute relation.



14
15
16
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 14

def relation
  @relation
end

Class Method Details

.validator_options(association, foreign_key) ⇒ Object



10
11
12
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 10

def self.validator_options(association, foreign_key)
  { attributes: association, foreign_key: foreign_key, message: VALIDATOR_MESSAGE }
end

Instance Method Details

#handle_foreign_key_error(instance) ⇒ Object



30
31
32
33
34
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 30

def handle_foreign_key_error(instance)
  # Hack to not query the database because we know the result already
  instance.send("#{relation}=", nil)
  instance.errors.add(relation, :blank, message: VALIDATOR_MESSAGE)
end

#keyString

Returns:

  • (String)


26
27
28
# File 'lib/database_validations/lib/db_belongs_to/belongs_to_options.rb', line 26

def key
  @key ||= Helpers.generate_key_for_belongs_to(column)
end