Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an attribute has a presence validation in Ruby on Rails

Is there a way to know if an attribute has a validation? Something like following:

Model.attribute.has_presence_validation?
like image 985
el_quick Avatar asked Aug 21 '14 16:08

el_quick


People also ask

How do I validate in Ruby on Rails?

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".

What is validate in rails?

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.

Can we save an object in DB if its validations do not pass?

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.

Why must you validate data before persisting it?

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.


2 Answers

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

like image 113
Abubakar Avatar answered Nov 15 '22 00:11

Abubakar


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)}
like image 37
lacco Avatar answered Nov 15 '22 01:11

lacco