class Cart
include Mongoid::Document
embeds_many :cart_items
def calculate_prices
# Set some fields
end
def remove_item(item)
# what goes here?
calculate_prices
save
end
end
class CartItem
include Mongoid::Document
embedded_in :cart
end
我希望remove_item
以原子方式从购物车中删除购物车商品,并在一个update
中为购物车集合设置一些新价格。
这可能吗?也许有些API用于标记要销毁的嵌入项目,然后保存购物车?
谢谢!
答案 0 :(得分:0)
这是可能的,先生。秘密在accepts_nested_attributes_for
:
class Cart
include Mongoid::Document
embeds_many :cart_items
attr_accessible ...
accepts_nested_attributes_for :cart_items
attr_accessible :cart_items_attributes
set_callback(:update, :before) do |document|
document.calculate_prices
end
protected
def calculate_prices
# Set some fields
end
end
class CartItem
include Mongoid::Document
embedded_in :cart
attr_accessible ...
end
在视图中:
= form_for @cart do |f|
= f.fields_for :cart_items do |n|
= render "cart_item", :n => n, :cart_item => n.object
通过它,您可以从购物车中删除商品,更新数量并在一个购物车update
中重新计算价格。