提前为另一个新手问题道歉,但ROR语法只是没有点击我,我无法理解快捷方式和惯例(尽管已经阅读了几本书!) -
我从一本书中有效地复制了这个,但是我想弄清楚什么是构建,创建等?
@cart = current_cart
product = Catalog::Product.find(params[:product_id])
Rails.logger.debug { "Value in cart id " + @cart.id.to_s }
@checkout_line_item = @cart.line_items.build(product: product)
respond_to do |format|
if @checkout_line_item.save...
日志的输出是:
Processing by Checkout::LineItemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9NH+xgDPTf/iN7RCdPd8H9rAIqWsSVB/f/rIT++Kk7M=", "product_id"=>"7"}
Created a line item
(0.1ms) BEGIN
SQL (2.0ms) INSERT INTO `checkout_carts` (`created_at`, `discounts`, `grand_total`, `loyalty_points`, `order_date`, `subtotal`, `timestamps`, `total_tax`, `updated_at`) VALUES ('2012-08-21 11:06:15', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2012-08-21 11:06:15')
(0.2ms) COMMIT
Catalog::Product Load (0.2ms) SELECT `products`.* FROM `products` WHERE `products`.`id` = 7 LIMIT 1
Value in cart id 8
Completed 500 Internal Server Error in 5ms
NoMethodError (undefined method `save' for nil:NilClass):
app/controllers/checkout/line_items_controller.rb:55:in `block in create'
app/controllers/checkout/line_items_controller.rb:54:in `create'
我猜测问题在于构建语法,它构建了结帐行项目,或者我可能设置了has_many关联错误。这对于某人帮助我排除故障是否足够?或者我应该发布模型声明吗?
使用模型更新:
class Checkout::LineItem < ActiveRecord::Base
attr_accessible :customer_update_date, :inventory_status, :line_item_color, :line_item_description, :line_item_size, :line_item_tagline, :line_item_total, :quantity, :sku_id, :style_id, :tax, :tax_code, :timestamps, :unit_price, :product
belongs_to :cart
belongs_to :product, :class_name => 'Catalog::Product'
end
class Checkout::Cart < ActiveRecord::Base
attr_accessible :discounts, :grand_total, :loyalty_points, :order_date, :subtotal, :timestamps, :total_tax
has_many :line_items, dependent: :destroy
end
module Catalog
class Product < ActiveRecord::Base
attr_accessible :assoc_product,:product_id, :merch_associations, :aux_description, :buyable, :long_description, :name, :on_special, :part_number, :release_date, :short_description, :withdraw_date, :occasion
<<clipped for brevity>>
has_many :line_items, :class_name => 'Checkout::LineItem'
...
end
不能回答我自己的问题,但我想我得到了答案:
看起来我需要将购物车添加到构建调用...
这似乎有效(我认为,还有另一个阻塞问题,但我可以对其进行排序):
@cart = current_cart
product = Catalog::Product.find(params[:product_id])
Rails.logger.debug { "Value in cart id " + @cart.id.to_s }
@checkout_line_item = @cart.line_items.build(product: product, cart: @cart)
答案 0 :(得分:0)
Build
实际上为空白对象创建并保留空间。这允许您创建关联对象而不保存它。我经历过的唯一用例是嵌套表单,其中我有一个事件的多个日期,所以我使用5times.build创建了5个空日期关联。