Is there a way to know if an attribute has a validation? Something like following:
Model.attribute.has_presence_validation?
This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".
In Rails, validations are used in order to ensure valid data is passed into the database. Validations can be used, for example, to make sure a user inputs their name into a name field or a username is unique.
If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
Data validation (when done properly) ensures that data is clean, usable and accurate. Only validated data should be stored, imported or used and failing to do so can result either in applications failing, inaccurate outcomes (e.g. in the case of training models on poor data) or other potentially catastrophic issues.
Well not sure about simplest solution but I achieved this functionality with quite complexity. Maybe someone come up with some simpler solution. Here is the code which worked perfectly for me.
I get all the validations on a model, chose presence validations(ActiveRecord::Validations::PresenceValidator) and then select all of their attributes and used include to check attribute(:your_attribute)presence in this array
Model.validators.collect{|validation| validation if validation.class==ActiveRecord::Validations::PresenceValidator}.compact.collect(&:attributes).flatten.include? :your_attribute
you can change compare statement
validation.class==ActiveRecord::Validations::PresenceValidator
to get all other types validation i.e uniqueness etc
For me, the following code is working (it is basically checking if any validator for given field is an instance of the presence validator):
MyModel.validators_on(:my_attribute).any?{|validator| validator.kind_of?(ActiveModel::Validations::PresenceValidator)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With