I’m building an ecommerce application with inventory control and a shopping cart. When the payment has been approved, I want to decrement the quantity of each of the products in the cart. This means, I need to decrement the product quantity column which belongs to line_items which belongs to carts.
I can decrement one through the active record interface like this (in my cart model):
self.line_items[0].product.decrement(:qty)
And also by executing a query directly:
connection.execute("UPDATE products SET qty = qty - 1 WHERE id IN (SELECT product_id FROM line_items WHERE cart_id = #{self.cart_id})")
But both of these methods don’t seem right. The latter queries the db schema directly which is obviously not the best practice. The first method is better but I don’t know how to implement it on all the records.
My models are like so:
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
The schema is:
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
I am sure there is an elegant way to do this. Can anyone help me please?
Many thanks,
Rim
How about update_counters? http://apidock.com/rails/ActiveRecord/CounterCache/update_counters