James P McGrath
James P McGrath

Reputation: 1884

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?

Upvotes: 4

Views: 1521

Answers (2)

Ryan Bigg
Ryan Bigg

Reputation: 107728

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

Upvotes: 10

monocle
monocle

Reputation: 5896

Well, I don't know if this is a 'good' way, but you can initialize a new object, call #valid? on it and then call #errors to get a hash of attributes and error messages. Then you'd have to parse those errors messages.

user = User.new
user.valid?
errors_hash = user.errors

Upvotes: 2

Related Questions