验证ActiveRecord属性长度取决于其他Object属性

时间:2012-04-26 02:38:01

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

如果当前对象的:phone设置为country_code,我正在尝试创建一个验证,强制ES字段为9位长。

我试图做这样的事情,但它不起作用。

validates_length_of :phone, :is => 9, :message => "number needs to be at least 9 digits." if self.country_code == "ES"

1 个答案:

答案 0 :(得分:2)

我认为你在寻找的是:

validates_length_of :phone, :is => 9,
:message => "number needs to be at least 9 digits.",
:if => "country_code == 'ES'"

或者

validates_length_of :phone, :is => 9,
:message => "number needs to be at least 9 digits.",
:if => Proc.new { |a| a.country_code == 'ES' }

查看文档here