Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inspect Validations that exist on ActiveRecord::Base Objects

I want to create a helper method to automatically output text_fields with a :maxlength attribute. I want this maxlegth to be set based on the :max specified in the field attributes validates_length validation, so as to remain DRY.

My question is: Is there a good way to inspect the validations that are present on an objects attribute, and then extract the maximum length from that validation.

I also plan on extracting other things like the regex from validates_format so I can set an attribute on the text_field, which can then be used by js to run client side validations.

Thanks.

Bonus points: Why doesn't Rails Automatically add the maxlength to text fields for us?

like image 376
James P McGrath Avatar asked Dec 21 '22 21:12

James P McGrath


1 Answers

In Rails 3 you can call the _validators method on an object to get the list of validators that will run:

t = Ticket.new
t._validators
like image 97
Ryan Bigg Avatar answered Apr 29 '23 01:04

Ryan Bigg