I am trying to add items to a cart. I keep getting
Undefined local variable or method
document_id' for #<Cart:0x8fc0130> Rails.root: C:/Users/cmendla/RubymineProjects/technical_library app/models/cart.rb:22:inadd_item' app/controllers/carts_controller.rb:7:in `add_to_cart' Request Parameters: {"_method"=>"post",
cart.rb
has_many :items
def add_item(product_id)
$test1 = 'add item 2'
item = items.where('document_id = ?', document_id).first
if item
increase the quantity of product in cart
item.quantity + 1
save
else
product does not exist in cart
product = Product.find(product_id)
items << product
document = Document.find(document_id)
items << document
cart.items << Item.new(document_id: document_id)
end
save
end
Application controller:
application_controller.rb
def current_cart
if session[:cart_id]
@current_cart ||= Cart.find(session[:cart_id])
end
if session[:cart_id].nil?
@current_cart = Cart.create!
session[:cart_id] = @current_cart.id
end
@current_cart
end
.
class Item < ActiveRecord::Base
belongs_to :cart
end
carts controller:
def add_to_cart
# @cart = current_cart
current_cart.add_item(params[:document_id])
redirect_to carts_path(current_cart.id)
# redirect to shopping cart or whereever
end
Routes.rb
post '/add_to_cart/:doc_id' => 'carts#add_to_cart', :as => 'add_to_cart'
Schema:
create_table "items", force: :cascade do |t|
t.integer "document_id"
t.string "user"
t.integer "cart_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "items", ["cart_id"], name: "index_items_on_cart_id"
create_table "carts", force: :cascade do |t|
t.string "user"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
I am calling the add action with the following link in my documents.index
<td><%= link_to "add", add_to_cart_path(document.id), :method => :post %></td>
document_idparameter in theadd_itemmethod. Also you passing in the controllerparams[:document_id]asproduct_idparameter of this method.