2012-01-31 113 views
0

我正在構建一個包含庫存控制和購物車的電子商務應用程序。當付款獲得批准後,我想減少購物車中每個產品的數量。這意味着,我需要減少屬於屬於購物車的line_items的產品數量列。Ruby on Rails - 通過活動記錄has_many協會減少列

我可以遞減一個通過這樣的活動記錄界面(在我的車模型):通過直接執行查詢

self.line_items[0].product.decrement(:qty) 

而且也:

connection.execute("UPDATE products SET qty = qty - 1 WHERE id IN (SELECT product_id FROM line_items WHERE cart_id = #{self.cart_id})") 

這些方法唐但兩者看起來不錯。後者直接查詢db模式,這顯然不是最佳實踐。第一種方法更好,但我不知道如何在所有記錄上實現它。

我的模型,像這樣:

class Product < ActiveRecord::Base 
end 

class Cart < ActiveRecord::Base 
    has_many :line_items 
end 

class LineItem < ActiveRecord::Base 
    belongs_to :cart 
    belongs_to :product 
end 

的模式是:

create_table "carts", :force => true do |t| 
    .. 
end 

create_table "line_items", :force => true do |t| 
    .. 
    t.integer "product_id" 
    t.integer "cart_id" 
end 

create_table "products", :force => true do |t| 
    .. 
    t.integer "qty" 
end 

我相信有一個優雅的方式來做到這一點。任何人都可以幫助我嗎?

非常感謝,
沿岸

回答

3

如何update_counters? http://apidock.com/rails/ActiveRecord/CounterCache/update_counters

class Cart < ActiveRecord::Base 
    has_many :line_items 
    has_many :products, :through => :line_items 
end 

Product.update_counters(cart.products, :qty => -1) 
# => UPDATE "products" SET "qty" = COALESCE("qty", 0) - 1 WHERE "products"."id" IN (1, 2) 
+0

我知道會有這樣一個很好的整潔的答案。這就是我喜歡鐵軌的原因。非常感謝您的幫助! – Rimian 2012-01-31 23:20:57