gpt4 book ai didi

ruby-on-rails - rails 3 : How to validate that A < B where A and B are both model attributes?

转载 作者:行者123 更新时间:2023-12-04 06:04:30 24 4
gpt4 key购买 nike

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

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 不是。)

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

在 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

关于ruby-on-rails - rails 3 : How to validate that A < B where A and B are both model attributes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4545102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com