我正在创建一个基于 Agile Web Development With Rails(版本 3)中的购物车。我设置了将“项目”添加到“购物车”的位置,然后在开始结帐过程时,将它们作为“line_items”添加到“订单”对象中。“line_items”代表任意数量的一个“项目”。到目前为止,我并没有偏离书中的例子。但是,这对我来说变得复杂了。我商店中的每个“项目”都可以使用文本进行自定义,我需要能够将自定义文本与“订单”中的“line_items”一起存储。
如上所述,“line_items”包含任意数量的“item”,但客户需要能够自定义每个 item,因此每个“line_item”必须为每个单独的“item”保存不同的自定义。因此,“line_items”表中不能只有一列用于自定义。我决定组织它的方式是创建一个新模型/表“line_item_attributes”。对于“line_item”中的每个“item”,都有一个新的“line_item_attributes”。
我对 Rails 还是很陌生,我在让它工作时遇到了一些麻烦。我不相信我什至以“正确的方式”做这件事。我遇到的是一种鸡/蛋问题。当我创建“订单”时,我将购物车中的“项目”添加为“line_items”。现在为了定制他们订购的产品,我还必须在每个“line_item”中添加“line_item_attributes”,以便定制表单可以使用。
以下是我不知道的:客户提交表单后,我不知道如何“填写”空白的“line_item_attributes”。我无法为表单创建“虚拟”line_item_attributes,然后在提交时从提交的数据中创建新的(实际保存的)。这样做的原因是它们必须绑定到它们所属的“line_items”中。我曾希望当我调用“@order.save”时 Rails 会填写它们,但事实并非如此。我希望这并不难理解。
我在下面包含了相关的代码:
购买.rb(控制器)
-SNIP-
def purchase
@cart = find_cart
if @cart.items.empty?
redirect_to_index("Your order is empty")
end
end
def customize
@renderable_partials = [1, 2, 3]
@order = find_order
if @order.nil?
redirect_to_index("Your order is empty")
end
end
def save_purchase
@cart = find_cart
@order = find_order(params[:cart_owner])
@order.add_line_items_from_cart(@cart)
redirect_to :action => 'customize'
end
def save_customize
@order = find_order
if @order.save
redirect_to :action => 'purchase'
else
flash[:error] = "Your information could not be saved"
redirect_to :action => 'customize'
end
end
-SNIP-
order.rb(模型)
class Order < ActiveRecord::Base
has_many :line_items
has_many :line_item_attributes
accepts_nested_attributes_for :line_items
accepts_nested_attributes_for :line_item_attributes
def add_line_items_from_cart(cart)
cart.items.each do |item|
li = LineItem.from_cart_item(item)
line_items << li
end
end
end
line_item.rb (模型)
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :item
has_many :line_item_attributes
accepts_nested_attributes_for :line_item_attributes
def self.from_cart_item(cart_item)
li = self.new
li.item = cart_item.item
li.quantity = cart_item.quantity
li.total_price = cart_item.price
li.quantity.times do |single_item|
lia = LineItemAttribute.new
li.line_item_attributes << lia
end
li
end
end
line_item_attributes.rb(模型)
class LineItemAttribute < ActiveRecord::Base
belongs_to :order
belongs_to :line_item
end
谢谢你的帮助!