Reputation: 17834
class CartItemsController < ApplicationController
before_filter :initialize_cart, :check_not_signedin
def create
product = Product.find(params[:product_id])
kart = initialize_cart
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
if qty == 0
@item = CartItem.new(:cart_id => kart.id, :product_id => product.id, :quantity => qty+1)
if @item.save
flash[:success] = "Product added"
redirect_to category_products_path
end
else
if CartItem.where("cart_id = ? AND product_id = ?", kart.id, product.id).first.update_column(:quantity, qty+1)
flash[:success] = "Product updated"
redirect_to category_products_path
end
end
end
When I am trying to run this I'm getting the following error "Can't convert FixNum into Array" app/controllers/cart_items_controller.rb:17:in `create'
Please help!
Upvotes: 3
Views: 265
Reputation: 8815
The following line should return a ActiveRecord::Relation
into qty
:
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
You should use qty.count
instead: qty.count == 0
Also, you can't add a ActiveRecord::Relation
with 1
like this: qty+1
. It will give you the error message you had.
I'm not sure what you are trying to do, but I suggest you use the debugger
gem to help you troubleshoot your problem. Follow the guide here to setup, it's very simple to setup: http://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debugger-gem
Then, place debugger
in your code:
product = Product.find(params[:product_id])
kart = initialize_cart
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
debugger # <---- here
if qty == 0
@item = CartItem.new(:cart_id => kart.id, :product_id => product.id, :quantity => qty+1)
if @item.save
Then you can find out more while you stopped at the debugger breakpoint, you can do stuff like:
qty.class
qty.count
# etc
Also, you can run rails console
for testing.
Upvotes: 3
Reputation: 690
I'm guessing that the following line is returning an Array:
CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
If this is the case then you can't simply add +1 to it on this line:
if CartItem.where("cart_id = ? AND product_id = ?", kart.id, product.id).first.update_column(:quantity, qty+1)
If this is not the case, can you point out which line is number 17 as pointed out in the error message.
Upvotes: 1