Rails 3:如何验证 A <B 其中 A 和 B 都是模型属性? [英] Rails 3: How to validate that A &lt; B where A and B are both model attributes?

查看:46
本文介绍了Rails 3:如何验证 A <B 其中 A 和 B 都是模型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证 customer_price >= my_price.我尝试了以下方法:

I would like to validate that customer_price >= my_price. I tried the following:

class Product < ActiveRecord::Base
  attr_accessor :my_price
  validates_numericality_of :customer_price, :greater_than_or_equal_to => my_price
  ...
end

(customer_price 是数据库中 Products 表中的一列,而 my_price 不是.)

(customer_price is a column in the Products table in the database, while my_price isn't.)

结果如下:

NameError in ProductsController#index
undefined local variable or method `my_price' for #<Class:0x313b648>

在 Rails 3 中执行此操作的正确方法是什么?

What is the right way to do this in Rails 3 ?

推荐答案

创建自定义验证器:

validate :price_is_less_than_total

# other model methods

private

  def price_is_less_than_total
    errors.add(:price, "should be less than total") if price > total
  end

这篇关于Rails 3:如何验证 A <B 其中 A 和 B 都是模型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆