Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of validation rules in Rails 3?

I need to get a list of validation rules out of a Model in my Rails application. I have searched around and looked through the source of a few client-side validation gems, but am still scratching my head about how to do this. Is there an easy way to just pull a list of validation rules out of a Rails model?

My specific use case is creating an API where the entry form for new items will be auto-generated from the Model definition, and I need to be able to express which fields are required, max length, etc. I already have fields, types, and length from the columns method, but there does not seem to be any type of similar validations method that returns what I need (mainly, required fields as enforced with validates and validates_presence_of, etc.).

like image 352
Vance Lucas Avatar asked Jan 05 '12 19:01

Vance Lucas


1 Answers

Check out the #validators and #validators_on methods:

http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html

You will have to write some custom code that operates on the returned objects and determines which attributes are required, i.e. which ones have validates_presence_of.

like image 177
rlkw1024 Avatar answered Oct 18 '22 01:10

rlkw1024