开发者

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

开发者 https://www.devze.com 2023-01-25 05:43 出处:网络
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 va

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 开发者_StackOverflowplan 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?


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消