开发者

In Mongoid, can you atomically destroy an embedded document and update its parent?

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

I would like the remove_item to atomically remove the cart item from the cart and set some new prices in one update to the carts collection.

Is that possible? Maybe some API to mark an embedded item for destroy and t开发者_开发问答hen save the cart?


That is possible, sir. The secret is in 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

In the view:

= form_for @cart do |f|
  = f.fields_for :cart_items do |n|
    = render "cart_item", :n => n, :cart_item => n.object

With that you can delete items from cart, update quantities and recalculate prices in a one single cart update.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜