我有两个班级,分别是存款和出价,它们分别为:
class Bid < ActiveRecord::Base
belongs_to :deposit
end
和
class Deposit < ActiveRecord::Base
has_many :bids
end
沉积物具有在创建时设置的固定量。出价也有金额,我正在尝试使用验证来确保bid.amount小于其所属的存款金额。
我尝试通过以下方法实现这一目标:
class Bid < ActiveRecord::Base
validates :amount, numericality: { only_integer: true, less_than_or_equal_to: self.deposit.amount }
end
但这给了我NoMethodError。我也尝试使用代码块,但也无法使它正常工作。我猜问题的一部分是记录还没有完全创建,但是我找不到有关该问题的任何信息。
如何基于关联的记录值进行这种验证?
通过添加您自己的验证方法validate
(请注意:单数)。
class Bid < ActionRecord::Base
validate :my_thing
def my_thing
unless self.my_condition
errors.add :field, :message
end
end
end
请参阅http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句