title: RoR ActiveRecord/ActiveRelation error: undefined method + for nilClass
body: <p>I'm honestly more lost than I have ever been programming ever. Recently, I've been attempting to move away from 5+ years of PHP development and try Ruby/Rails. I picked up Agile Web Development with Rails and I've been following along with it. Versions I carry that differ include Mac OS X Snow Leopard (originally, having migrated to Mountain Lion) and Ruby/Rails 1.8.7/3.2.6. </p>
  
  <p>When adding quantity to the cart, my code appears as so:
  cart.rb (model)</p>
  
  <pre><code>class Cart &lt; ActiveRecord::Base
    has_many :line_items, :dependent =&gt; :destroy
  
    def add_product(product_id)
      current_item = line_items.find_by_product_id(product_id)
      if current_item
        current_item.quantity += 1
      else
        current_item = line_items.build(:product_id =&gt; product_id)
      end
      current_item
    end
  end
  </code></pre>
  
  <p>I have attr_accessible :quantity within the line_item.rb model and within line_items_controller.rb I'm calling @line_item = current_cart.add_product(product.id). The code is perfectly function the first time you add a product to the cart, yet the second time Rails gives me the error:</p>
  
  <pre><code>undefined method `+' for nil:NilClass
  </code></pre>
  
  <p>and points to the obvious line in questions (above with the plus). Any suggestions? Thanks.</p>
  
  <p>EDIT: If anyone can also recommend in the comments if this is the best route to learning Rails, or if I should pick up another book or use another website/etc., because this isn't the first time that code has been wrong in this book. </p>
  
  <p>EDIT 2: Excerpted line_items_controller.rb (lines 40-56)</p>
  
  <pre><code>def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    @line_items = @cart.add_product(product.id) #product.id, product didn't work.
  
    respond_to do |format|
      if @line_item.save
        format.html { redirect_to @line_item.cart, :notice =&gt; 'Line item was successfully created.' }
        format.json { render :json =&gt; @line_item, :status =&gt; :created, :location =&gt; @line_item }
      else
        format.html { render :action =&gt; "new" }
        format.json { render :json =&gt; @line_item.errors, :status =&gt; :unprocessable_entity }
      end
    end
  end
  </code></pre>
  
  <p>Also, since the code works for one item but not sequential additions of the same item, I don't think it has to do with .save.</p>