LineItemsController中的ActionController :: ParameterMissing #create

时间:2016-04-23 23:09:07

标签: ruby-on-rails ruby

在我的rails应用程序中,我有用户可以添加到购物车的产品。购物车中的产品由行项目表示。

当用户正在查看产品时,他们可以选择将产品作为订单项添加到购物车。

我在尝试创建新的订单项实例时收到错误消息。我可以使用一些帮助来理解为什么我会收到此错误以及我可以做些什么来解决它。

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' 

Product 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

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

1 个答案:

答案 0 :(得分: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})