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.
When adding quantity to the cart, my code appears as so:
cart.rb (model)
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :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 => product_id)
end
current_item
end
end
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:
undefined method `+' for nil:NilClass
and points to the obvious line in questions (above with the plus). Any suggestions? Thanks.
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.
EDIT 2: Excerpted line_items_controller.rb (lines 40-56)
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 => 'Line item was successfully created.' }
format.json { render :json => @line_item, :status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.json { render :json => @line_item.errors, :status => :unprocessable_entity }
end
end
end
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.
Did you make sure quantity is not nil.
try
instead of