Has_One关联不创建

时间:2014-06-19 05:19:47

标签: ruby-on-rails

一旦条纹费用通过,我想创建订单(基于之前的名为order_preview的模型)

我的购物车模型如下:

has_one :order_preview
has_one :order

我知道你应该使用@ var.build_model而不是@ var.model.build。 这是我的代码......

@cart.create_order(
            :name => @order_preview.name,
            :email => @order_preview.email,
            :address => @order_preview.address,
            :address2 => @order_preview.address2,
            :city => @order_preview.city,
            :state => @order_preview.state,
            :zip => @order_preview.zip,
            :country => @order_preview.country,
            :permalink => @order_preview.permalink,
            :shipping_type => @order_preview.shipping_type,
            :shipping_price => @order_preview.shipping_price,
            :grand_total => @amount,
            :cart => @cart,
            :items => @cart.line_items.to_a
            )
@cart.save
redirect_to cart_order_path

这似乎有效,我甚至使用更好的错误来“提出”错误,看看保存后,@ cart.order没有显示为零。列出了上述所有信息。但是,在重定向之后,@ cart.order

的结果为零
def show
    @cart = current_cart
    @order = @cart.order
    @line_items = @order.items
end

@cart给了我想要的东西,但是@ cart.order = nil。 我在俯瞰什么?它必须是简单的......

注意:build_order无效,所以我尝试了create_order

1 个答案:

答案 0 :(得分:1)

尝试:

@cart = current_cart
@order = @cart.build_order(
          :name => @order_preview.name,
          :email => @order_preview.email,
          :address => @order_preview.address,
          :address2 => @order_preview.address2,
          :city => @order_preview.city,
          :state => @order_preview.state,
          :zip => @order_preview.zip,
          :country => @order_preview.country,
          :permalink => @order_preview.permalink,
          :shipping_type => @order_preview.shipping_type,
          :shipping_price => @order_preview.shipping_price,
          :grand_total => @amount, 
          :items => @cart.line_items.to_a
          )
if @order.save
  redirect_to cart_order_path
else
  render your_form
end

你的@ cart.order是零,因为它没有将它保存在数据库中。我还已删除 :cart => @cart,因为当您执行@ cart.build_order时,它会自动将其与该购物车相关联