今天只是一个(希望)快速的,如果它非常简单并且我只是很厚,我会道歉。
我有一个我正在处理的基本电子商务应用,并且有两个问题:
到目前为止,这是我的模特协会:
Customer
has_one :cart
has_many :orders
Product
has_many :cart_items
Cart
belongs_to:customer
has_many :cart_items
CartItem
belongs_to :product
belongs_to :cart
到目前为止我只有脚手架所以我目前的所有代码都是开箱即用的Rails 3.2.14。
我只是不确定如何让:cart_items与:产品互动,反之亦然。我应该添加什么代码/额外功能才能使其正常工作?谢谢你的帮助。
答案 0 :(得分:0)
假设CartItem
belongs_to :product
(似乎很可能),并且quantity
属性指示购物车中的数字:
1)我相信你想要的功能可以通过CartItem
上的回调来完成。例如,
class CartItem < AR:B
after_save :remove_from_stock
after_destroy :return_to_stock
def remove_from_stock
product.stock -= self.quantity
product.save
end
def return_to_stock
product.stock += self.quantity
product.save
end
end
2)当您显示CartItem
时,只需参考相关产品:
<% @cart_items.each do |cart_item| %>
Item Name: <%= cart_item.product.name %>
Item Price: <%= cart_item.product.price %>
<% end %>
这样,对关联Product
的任何更改都将反映在引用它的任何视图中。
如果您一次显示多个,请确保使用预先加载以避免N + 1个查询:
@cart_items = CartItem.includes(:product).where(<whatever>)