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