我有两个想要保持同步的模型的属性。
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并在after_save调用的方法中执行update_attributes,它会启动一个无限循环并使应用程序崩溃。
如果我想要更新很多列,我该如何实现呢?
我知道一种解决方案是使用update_column -但它只适用于1列。
有什么想法?
发布于 2013-01-26 04:03:45
您可以在每个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)
endhttps://stackoverflow.com/questions/14528883
复制相似问题