0

我有一个错误,但我无法查明来源:(我第一次使用 add_to_cart 操作时它工作正常,但第二次我遇到此错误。

Started GET "/home/add_to_cart?id=5&money=USD" for 10.0.1.3 at 2013-05-26 17:22:42 +0200
 Processing by HomeController#add_to_cart as HTML
 Parameters: {"id"=>"5", "money"=>"USD"}
 Completed 500 Internal Server Error in 2ms

NoMethodError (undefined method `+' for nil:NilClass):
  app/models/cart.rb:14:in `add_artwork'
  app/controllers/home_controller.rb:39:in `add_to_cart'

似乎@cart 对象丢失了或其他东西......或者对象“艺术品”丢失了......我不知道......

控制器

def add_to_cart
  artwork = Artwork.find(params[:id])
  @cart = find_or_create_cart
  @cart.add_artwork(artwork)   #--- line 39
  redirect_to(:action => 'show_cart')
end

def show_cart
  @cart = find_or_create_cart
end

private

def find_or_create_cart
  session[:cart] ||= Cart.new
end  

购物车.rb

class Cart

  attr_reader :items
  attr_reader :total_price

  def initialize
     @items = []
     @total_price = 0.0
  end

  def add_artwork( artwork )
    @items << LineItem.new_based_on(artwork)
    @total_price += artwork.price   #---- line 14
  end
end

line_item.rb

class LineItem < ActiveRecord::Base

  belongs_to :artwork
  belongs_to :order

  def self.new_based_on ( artwork  )
    line_item = self.new
    line_item.artwork = artwork
    line_item.price = artwork.price
    return line_item
  end
end

session_store.rb

  Larrabyblaine::Application.config.session_store :active_record_store
4

3 回答 3

1

如果没有初始值,您将无法使用+=on 。@total_price

只需在第 14 行之前添加一行

@total_price ||= 0 
@total_price += artwork.price   #---- line 14
于 2013-05-26T16:07:28.067 回答
0

似乎是对象艺术品太大并导致了错误。

如果我更换

 line_item.artwork = artwork

通过(在数据库中进行相应的修改)

 line_item.title = artwork.title

它完美地工作。如果有人对如何通过会话管理大对象有任何想法,我都会听到。

于 2013-05-27T10:42:50.307 回答
0

试试这个,

@total_price = if @total_price 
@total_price += artwork.price
else
artwork.price
end
于 2013-06-05T04:45:42.477 回答