Ruby on Rails - 通过活动记录 has_many 关联减少列
我正在构建一个具有库存控制和购物车的电子商务应用程序。当付款被批准后,我想减少购物车中每种产品的数量。这意味着,我需要减少属于购物车的 line_items 的产品数量列。
我可以通过活动记录接口递减一个,如下所示(在我的购物车模型中):
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})")
但这两种方法似乎都不正确。后者直接查询数据库模式,这显然不是最佳实践。第一种方法更好,但我不知道如何在所有记录上实现它。
我的模型是这样的:
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
我确信有一种优雅的方法可以做到这一点。有人可以帮我吗?
非常感谢,
轮缘
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
update_counters怎么样? http://apidock.com/rails/ActiveRecord/CounterCache/update_counters
How about update_counters? http://apidock.com/rails/ActiveRecord/CounterCache/update_counters