简体   繁体   English

验证Rails 3.1模型中的数据

[英]Validates Data in Rails 3.1 model

My application use two varariables to take notes about product warranty start time and warranty end time;so in my view I use two dropdown menu to select start and end times. 我的应用程序使用两个变量来记录有关产品保修开始时间和保修结束时间的信息;因此在我看来,我使用两个下拉菜单选择开始和结束时间。 Now, I must sure that start time shouldn't greater than end time. 现在,我必须确保开始时间不应大于结束时间。 In witch way can I model this restriction? 我可以以巫婆的方式对此限制建模吗? I've tried with the following code in my model file: 我已经在模型文件中尝试使用以下代码:

  validates_numericality_of :warranty_end, :greater_than => :warranty_start 

but I've seen that it doesn't work! 但我已经看到它行不通! Any suggestions? 有什么建议么?

I don't think that you can use variables in validates like that, but you can create a custom validator like this 我不认为您可以在validates使用变量,但是可以像这样创建自定义验证器

validates_numericality_of :warranty_end
validate :warranty_end_less_than_warranty_start

...

def warranty_end_less_than_warranty_start
  unless warranty_end > warranty_start
    errors.add :warranty_end, "must be before the warranty starting date"
  end
end

That should work (in 3.2 at least). 那应该工作(至少在3.2中)。 From the docs at http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html : 从位于http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html的文档中:

validates_numericality_of :width, :less_than => Proc.new { |person| person.height } 
validates_numericality_of :width, :greater_than => :minimum_weight

Thank you Azolo now it's works! 谢谢Azolo,现在一切正常! The only thing is that you delete "validates_numericality_of :warranty_end" statement, so working code for me is: 唯一的事情是您删除了“ validates_numericality_of:warranty_end”语句,因此对我来说有效的代码是:

validate :warranty_end_less_than_warranty_start

...

def warranty_end_less_than_warranty_start
  unless warranty_end > warranty_start
    errors.add :warranty_end, "must be before the warranty starting date"
  end
end

Thank you all again 再次谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM