2016-04-23 42 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

相关问题