Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get validations from model

How cat I get list of validations defined in model

Example:

class ModelName   validates_presence_of :field_name   validates_inclusion_of :sex, :in => %w(M F) end 

I need Hash like:

{:field_name => 'required', :sex => 'Must be in: M, F'} 
like image 820
manzhikov Avatar asked Oct 29 '10 12:10

manzhikov


People also ask

How do you check the validity of a model?

Gathering evidence to determine model validity is largely accomplished by examining the model structure (i.e., the algorithms and relationships) to see how closely it corresponds to the actual system definition. For models having complex control logic, graphic animation can be used effectively as a validation tool.

What is model validation explain?

Model validation is the process by which model outputs are (systematically) compared to independent real-world observations to judge the quantitative and qualitative correspondence with reality.

What can model validation be used for?

The purpose of model validation is to check the accuracy and performance of the model basis on the past data for which we already have actuals.


2 Answers

You don't need a plugin for basic needs.

You can do this to get a hash of all validators.

ModelName.validators 

If you want to get the validators for a specific field :

ModelName.validators_on(:attribute) 
like image 158
Nicolas Blanco Avatar answered Oct 18 '22 00:10

Nicolas Blanco


This code yields an array of required fields. It should be adaptable to your needs.

@required_fields = [] ModelName.validators.each do |v|   @required_fields << v.attributes.first if v.kind == :presence end 
like image 30
Jussi Hirvi Avatar answered Oct 17 '22 23:10

Jussi Hirvi