2
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 可以将嵌入的项目标记为销毁然后保存购物车?

4

1 回答 1

1

这是可能的,先生。秘诀在于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

于 2011-04-30T18:36:17.460 回答