在Mongoid中,你可以自动销毁嵌入式文档并更新其父级吗?

时间:2011-04-30 18:07:16

标签: ruby mongodb persistence mongoid destroy

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用于标记要销毁的嵌入项目,然后保存购物车?

谢谢!

1 个答案:

答案 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中重新计算价格。