控制器/未定义局部变量

时间:2016-01-08 18:46:11

标签: ruby-on-rails

我正在尝试将商品添加到购物车中。我一直在

  

未定义的局部变量或方法document_id' for #<Cart:0x8fc0130> Rails.root: C:/Users/cmendla/RubymineProjects/technical_library app/models/cart.rb:22:in add_item&#39;   app / controllers / carts_controller.rb:7:在`add_to_cart&#39;请求   参数:   {&#34; _method&#34; =&gt;&#34; post&#34;,

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.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

推车控制器:

  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'

架构:

 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

我在我的documents.index

中使用以下链接调用add动作
<td><%= link_to "add",  add_to_cart_path(document.id), :method => :post %></td> 

1 个答案:

答案 0 :(得分:1)

item = items.where('document_id = ?', document_id).first

在该行上没有定义document_id。应该实际上是product_id吗?