0

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

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.

问题在于记录的更新。

如果我在调用的方法中调用 anafter_save并执行 an ,它将启动无限循环并使应用程序崩溃。update_attributesafter_save

鉴于我想更新许多列,我该如何实现?

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

想法?

4

1 回答 1

1

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

可能看起来像这样:

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
于 2013-01-25T20:03:44.640 回答