0

エラーがありますが、ソースを特定できません:( add_to_cart アクションを初めて使用するときは正常に機能しますが、2回目にこのエラーが発生します。

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 行目の前に 1 行追加するだけです

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

これを試して、

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

オブジェクトのアートワークが大きすぎてバグが発生したようです。

私が交換する場合

 line_item.artwork = artwork

by (データベース内の対応する変更)

 line_item.title = artwork.title

それは完全に機能します。セッションで大きなオブジェクトを管理する方法について誰かが考えているなら、私はすべて聞いています。

于 2013-05-27T10:42:50.307 に答える