Reputation: 8348
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?
Upvotes: 2
Views: 757
Reputation: 12868
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
.
Upvotes: 1