Class: DatabaseValidations::DbPresenceValidator
- Inherits:
-
ActiveRecord::Validations::PresenceValidator
- Object
- ActiveRecord::Validations::PresenceValidator
- DatabaseValidations::DbPresenceValidator
- Defined in:
- lib/database_validations/lib/validators/db_presence_validator.rb
Constant Summary collapse
- REFLECTION_MESSAGE =
ActiveRecord::VERSION::MAJOR < 5 ? :blank : :required
Instance Attribute Summary collapse
-
#klass ⇒ Object
readonly
Returns the value of attribute klass.
Class Method Summary collapse
-
.kind ⇒ Symbol
Used to make 3rd party libraries work correctly.
Instance Method Summary collapse
- #apply_error(instance, attribute) ⇒ Object
-
#initialize(options) ⇒ DbPresenceValidator
constructor
A new instance of DbPresenceValidator.
- #perform_db_validation? ⇒ Boolean
-
#validate(record) ⇒ Object
TODO: add support of optional db_belongs_to.
Constructor Details
#initialize(options) ⇒ DbPresenceValidator
Returns a new instance of DbPresenceValidator.
15 16 17 18 19 20 21 22 |
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 15 def initialize() @klass = [:class] super Injector.inject(klass) Checkers::DbPresenceValidator.validate!(self) end |
Instance Attribute Details
#klass ⇒ Object (readonly)
Returns the value of attribute klass.
5 6 7 |
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 5 def klass @klass end |
Class Method Details
.kind ⇒ Symbol
Used to make 3rd party libraries work correctly
10 11 12 |
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 10 def self.kind :presence end |
Instance Method Details
#apply_error(instance, attribute) ⇒ Object
43 44 45 46 47 |
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 43 def apply_error(instance, attribute) # Helps to avoid querying the database when attribute is association instance.send("#{attribute}=", nil) instance.errors.add(attribute, :blank, message: REFLECTION_MESSAGE) end |
#perform_db_validation? ⇒ Boolean
24 25 26 |
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 24 def perform_db_validation? true end |
#validate(record) ⇒ Object
TODO: add support of optional db_belongs_to
29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/database_validations/lib/validators/db_presence_validator.rb', line 29 def validate(record) if record._database_validations_fallback super else attributes.each do |attribute| reflection = record.class._reflect_on_association(attribute) next if reflection && record.public_send(reflection.foreign_key).present? validate_each(record, attribute, record.public_send(attribute)) end end end |