如何获得 ActiveRecord 验证中配置的最大长度? [英] How to get the maximum length configured in an ActiveRecord validation?
本文介绍了如何获得 ActiveRecord 验证中配置的最大长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个模型:
class Person
validates_lenght_of :name, :maximum => 50
end
我有一些显示倒计时并强制执行此最大值的视图代码.但是我将数字 50 硬编码到该视图代码中.有没有办法从模型中提取这个数字?
I have some view code that shows a countdown and enforces this maximum. However I hard coded the number 50 into that view code. Is there a way to extract this number from the model?
类似于:
Person.maximum_length_of_name
我试过了:
Person.validators_on(:name)
=> [#<ActiveRecord::Validations::UniquenessValidator:0x000001067a9840 @attributes=[:name], @options={:case_sensitive=>true}, @klass=Trigger(id: integer, name: string, created_at: datetime, updated_at: datetime, user_id: integer, slug: string, last_update_by: integer)>, #<ActiveModel::Validations::PresenceValidator:0x000001067a6c30 @attributes=[:name], @options={}>, #<ActiveModel::Validations::LengthValidator:0x000001067a3f08 @attributes=[:name], @options={:tokenizer=>#<Proc:0x00000101343f08@/Users/sjors/.rvm/gems/ruby-1.9.2-p0/gems/activemodel-3.0.6/lib/active_model/validations/length.rb:9 (lambda)>, :maximum=>50}>]
信息在那里,但我不知道如何提取它:
The information is in there, but I don't know how to extract it:
推荐答案
irb(main):028:0> p Person.validators_on(:name)[0].options[:maximum]
50
=> 50
正如@Max Williams 提到的,它只适用于 Rails 3
As @Max Williams mentioned it works only on Rails 3
这篇关于如何获得 ActiveRecord 验证中配置的最大长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文