提前为另一个新手问题道歉,但 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)