0

Via such book:

Agile Web Development with Rails

i'm creating shopping cart for my application. There is such code:

class Cart < ActiveRecord::Base
    attr_accessible :id
    has_many :line_items, dependent: :destroy

  def add_article(article_id)
    current_item = line_items.find_by_ART_ID(article_id)
      if current_item
      current_item.quantity += 1
      else
      current_item = line_items.build(ART_ID: article_id)
      end
    current_item
  end
  def total_price
    line_items.to_a.sum { |item| item.total_price(item.ART_ID) }
  end
  def total_count
    line_items.to_a.sum { |item| item.quantity }
  end

end

On my previous project on rails 3.0.9 all was ok, but now it's say that

nil can't be coerced into Fixnum in db, quantity is null

if i change my code for like this

current_item = line_items.find_by_ART_ID(article_id)
          if current_item
          current_item.quantity = 1
          else
          current_item = line_items.build(ART_ID: article_id)
          current_item.quntity = 1
          end
        current_item

all is good, but what's wrong? why rails 3.2.6 and ruby 1.9.3 don't understand my += assignments?

4

1 回答 1

1

Its not a problem with += , the problem is you are try to do this with your code.

nil + 1

quantity is nil for the first time.

于 2012-08-13T13:04:42.913 回答