rails验证依赖模型

时间:2017-05-11 23:01:44

标签: ruby-on-rails ruby activerecord

有2个表:订单到达。订单上可以有很多到货。我想验证特定订单的到货数量的创建。

订单包含字段book_idquantity:integer

到达包含字段order:belongs_toquantity:integer

Order.rb:

class Order < ActiveRecord::Base
  has_many :arrivals

  def total_arrival_quantity
    arrivals.map(&:quantity).sum
  end

  def order_quantity_minus_arrival_quantity
    quantity - total_arrival_quantity
  end
end

Arrival.rb:

class Arrival < ActiveRecord::Base
  belongs_to :order

  validates :total_arrival_quantity_less_or_equal_to_order_quantity, on: create
  validates :current_arrival_quantity_less_or_equal_to_order_quantity, on: create

  def current_arrival_quantity_less_or_equal_to_order_quantity
    self.quantity <= order.quantity
  end
end

如何使两个验证有效?

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效,

validate :order_quantity, on: :create

private
def order_quantity
  if quantity > order.order_quantity_minus_arrival_quantity
    errors.add(:quantity, 'cannot be greater than ordered quantity.')
  end
end