Rails after_save无法正常工作(rails - 3.2.22.1)

时间:2017-09-22 13:22:58

标签: ruby-on-rails

我有OrderItem,SaleOrderItem和PurchaseOrderItem模型

class SaleOrderItem < OrderItem
  self.table_name = "order_items"
end

class PurchaseOrderItem < OrderItem
   self.table_name = "order_items"
end

class OrderItem < ActiveRecord::Base
  after_save :update_order

  def update_order
    is_pending = ord.order_items.
      where(state: [SaleOrderItem.on_orde, SaleOrderItem.carter]).count > 0
    self.order.update_column(:any_pending_order_items, is_pending)
  end
end

在以下情况下未调用save方法

so = SaleOrder.first
oi = so.order_items.first
oi.save   << This is not calling after_save on order items

在以下情况下调用save方法

oi2 = OrderItem.find(oi.id)
oi2.save << This calls after_save on order items

有人评论吗?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案 应该在SaleOrderItem和PurchaseOrderItem模型而不是OrderItem模型上调用after_save方法。所以它应该像是

class SaleOrderItem < OrderItem
  after_save :update_order << Here after_save added
  self.table_name = "order_items"
end

class PurchaseOrderItem < OrderItem
   after_save :update_order << Here after_save added
   self.table_name = "order_items"
end

class OrderItem < ActiveRecord::Base
              << Here after_save removed
  def update_order
    is_pending = ord.order_items.
      where(state: [SaleOrderItem.on_orde, SaleOrderItem.carter]).count > 0
    self.order.update_column(:any_pending_order_items, is_pending)
  end
end

这将修复在某些情况下未调用after_save