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 に答える