2016-04-23 44 views
0

在我的rails應用程序中,我有一個用戶可以添加到購物車的產品。購物車中的產品由行項目表示。ActionController :: ParameterMissing in LineItemsController#create

當用戶查看產品時,他們可以選擇將產品作爲訂單項添加到其購物車中。

我在嘗試創建新的訂單項實例時遇到錯誤。我可以使用一些幫助來理解爲什麼我得到這個錯誤以及我能做些什麼來解決它。

Processing by LineItemsController#create as HTML 
    Parameters: {"authenticity_token"=>"3TcxB2vPrhhEqF517yhejZgNSry0uhfjP6bF4Kifd4ofqgDSJH43wtDoNdqTINIkYz1YOx83gAii9Dr5NHgx1g==", "product_id"=>"product"} 
Completed 400 Bad Request in 1ms (ActiveRecord: 0.0ms) 

ActionController::ParameterMissing (param is missing or the value is empty: line_item): 
    app/controllers/line_items_controller.rb:72:in `line_item_params' 
    app/controllers/line_items_controller.rb:27:in `create' 

產品Catelog(index.html.slim),則button_to是其中正在創建LINE_ITEM

h1 My Products 

- @products.each do |product| 
    .entry 
    = image_tag(product.image_url) 
    h3 
     = product.title 
    h4 
     = product.description 
    .price_line 
     span.price 
     = number_to_currency(product.price, locale: :fr) 
     = button_to 'Add to cart', line_items_path(product_id: product) 

line_items_controller.rb

def create 
    @line_item = LineItem.new(line_item_params) 

     respond_to do |format| 
      if @line_item.save 
      format.html { redirect_to @line_item, notice: 'Line item was successfully created.' } 
      format.json { render :show, status: :created, location: @line_item } 
      else 
      format.html { render :new } 
      format.json { render json: @line_item.errors, status: :unprocessable_entity } 
      end 
     end 
     end 

    private 

     def line_item_params 
     params.require(:line_item).permit(:product_id, :cart_id) 
     end 

line_item.rb

class LineItem < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :cart 
end 

produ ct.rb

class Product < ActiveRecord::Base 
    has_many :line_items 
end 

模式

create_table "carts", force: :cascade do |t| 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "line_items", force: :cascade do |t| 
    t.integer "product_id" 
    t.integer "cart_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "products", force: :cascade do |t| 
    t.string "title" 
    t.text  "description" 
    t.string "image_url" 
    t.decimal "price",  precision: 8, scale: 2 
    t.datetime "created_at",       null: false 
    t.datetime "updated_at",       null: false 
    end 

回答

2

請檢查該線(index.html.slim最後一行)

= button_to 'Add to cart', line_items_path(product_id: :product)

你需要改變這樣的:

= button_to 'Add to cart', line_items_path(line_item: {product_id: product})

+0

我仍然得到相同的400錯誤 – adamscott

+0

@adamscott請參閱編輯答案。我第一次錯過了完整的錯誤日誌 – Alfie

+0

@adamscott這是否解決了您的問題? – Alfie

相關問題