如何在rails模型中比较输入值和数据库值?

时间:2017-12-12 10:07:09

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems ruby-on-rails-5

我有一个名为CustomizedBooking的模型,我需要验证付费金额等于数据库的价格列。 以下是代码段

validate :paid_amount_and_price
def paid_amount_and_price_check
    if paid_amount == price column value of the database
    errors.add(:paid_amount, "Must be equal to the price to process further!")
end

请!有人,建议我

2 个答案:

答案 0 :(得分:1)

我们不必在此处使用任何自定义验证,请尝试:

validates_numericality_of :paid_amount,
                          equal_to: ->(object) { object.price.to_f },
                          message: "Must be equal to the price to process further!"

validates :paid_amount, 
          :numericality => { equal_to: ->(object) { object.price.to_f },
                             message: "Must be equal to the price to process further!" }

答案 1 :(得分:0)

在模型中尝试以下代码:

validate :paid_amount_and_price
def paid_amount_and_price_check
    unless paid_amount.to_f == price.to_f
      errors.add(:paid_amount, "Must be equal to the price to process further!")
    end
end