Reputation: 33775
I have attributes on two models that I would like to keep in sync.
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>
Both of those share some attributes that are similar.
I have the creation aspect down - once a new record is created, I simply do an after_create
.
The issue is with the updating of the record.
If I call an after_save
and do an update_attributes
in the method called by the after_save
it starts an infinite loop and crashes the app.
How do I achieve that - given that I want to update many columns?
I know one solution is to use update_column
- but that just works with 1 column.
Thoughts?
Upvotes: 0
Views: 537
Reputation: 9700
You could temporarily deactivate the callback on the other model in each of your after_save
callbacks to avoid looping like this. For the details on doing this, see the second answer of this question How to skip ActiveRecord callbacks?
Would probably look something like this:
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
Upvotes: 1