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

发布于 2024-11-03 23:40:46 字数 431 浏览 0 评论 0原文

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 能够自动从购物车中删除购物车商品,并在购物车集合的一次更新中设置一些新价格。

这可能吗?也许有一些 API 可以将嵌入的项目标记为销毁,然后保存购物车?

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 then save the cart?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明媚如初 2024-11-10 23:40:46

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

通过该视图,您可以在单个购物车更新中删除购物车中的商品、更新数量并重新计算价格。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文