如何比较 rails 模型中的输入值与数据库值?

How to compare an input value with database value in rails model?

我有一个名为 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

拜托!有人,建议我

在模型中尝试以下代码:

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

我们不必在这里使用任何自定义验证,试试这个:

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!" }