如何获得配置在一个ActiveRecord验证的最大长度。 [英] How to get the maximum length configured in an ActiveRecord validation?
本文介绍了如何获得配置在一个ActiveRecord验证的最大长度。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个模式:
class Person
validates_lenght_of :name, :maximum => 50
end
我有一些看法code,显示倒计时并强制执行这个最大值。不过,我很难codeD数字50到该视图code。有没有办法从模型中提取这个数字?
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
我尝试这样做:
I tried this:
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:
推荐答案
使用 validators_on 方法
irb(main):028:0> p Person.validators_on(:name)[0].options[:maximum]
50
=> 50
由于@Max威廉姆斯提到它只能on Rails的3
As @Max Williams mentioned it works only on Rails 3
这篇关于如何获得配置在一个ActiveRecord验证的最大长度。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文