这个问题似乎没有得到任何关注:)
反正我想通去将不嵌入在order_item产品的最佳方式,但是从产品的复制相关领域order_item。
解决方案看起来像这样
class Product
include Mongoid::Document
# product fields like name, price, ...
belongs_to :category
end
class Order
include Mongoid::Document
# order fields like date, total_amount, address ...
embeds_many :order_items
end
class OrderItem
include Mongoid::Document
include Mongoid::MoneyField
embedded_in :order
# you can also store reference to original product
belongs_to :original_product
field :count, type: Integer
field :name
field :ean
field :sku
money_field :final_price
def self.from_product(product)
item = self.new
# ... assign fields from product, eg:
# item.name = product.name
item
end
end
而当用户点击“添加到购物车”,你可以做这样的事情:通过可视发生了什么
def add
# check if product is already in the cart
order_item = @order.items.detect {|item| item.product_id == params[:product_id]}
# if not, create from product in database
if order_item.nil?
product = Product.find(params[:product_id])
order_item = OrderItem.from_product(product)
# and add to items array
@order.items.push(order_item)
end
# set count that we got from product form
# (we can do this since order_item is
# also reference to the order_item inside array of order_items)
order_item.count = params[:count]
# emit event
event = Events::CartItemChanged.new(order_item: order_item, order: @order, request_params: params)
broadcast :cart_item_changed, event
# no need to call validations since we're just adding an item
@order.save! :validate => false
redirect_to cart_path
end
牛肉这了一点,然后随时接受你自己的答案。 –