对于不同型号,如何保持两条记录同步而不会陷入回调陷阱?

时间:2013-01-25 19:19:39

标签: ruby-on-rails ruby-on-rails-3

我有两个模型的属性,我希望保持同步。

1.9.3p194 :009 > p
 => #<Product id: 19, name: "Long Sleeve Blue", description: "<p>\tLong Sleeve Blue Flannel shirt comes in all siz...", price: 49.99, vendor_id: 12, created_at: "2012-12-15 23:35:05", updated_at: "2013-01-24 19:11:18", image: "shirt.png", sku: "ABC10034"> 
1.9.3p194 :010 > p.piggybak_sellable
 => #<Piggybak::Sellable id: 1, sku: "AR4590", description: "Blue Shirt", price: #<BigDecimal:7fa97cd63ff8,'0.2499E2',18(45)>, quantity: 100, item_id: 19, item_type: "Product", active: true, unlimited_inventory: false> 

这两者都有一些相似的属性。

我将创建方面缩小 - 一旦创建了新记录,我只需执行after_create

问题在于更新记录。

如果我拨打after_save并在update_attributes调用的方法中执行after_save,则会启动无限循环并崩溃该应用。

我如何实现这一点 - 假设我想要更新许多列?

我知道一种解决方案是使用update_column - 但这只适用于1列。

思想?

1 个答案:

答案 0 :(得分:1)

您可以在每个after_save回调中暂时停用其他模型上的回调,以避免像这样循环。有关执行此操作的详细信息,请参阅此问题的第二个答案How to skip ActiveRecord callbacks?

可能看起来像这样:

after_save :update_product

def update_product
  Product.skip_callback(:save, :after, :update_other)
  p = Product.find_by_whatever(self.whatever)
  p.update_attributes(:one => self.one, :two => self.two)
  Product.set_callback(:save, :after, :update_other)
end