adamscott adamscott - 7 months ago 29
Ruby Question

ActionController::ParameterMissing in LineItemsController#create

In my rails application, I have Products that a user can add to a Cart. The Products in the Cart are represented by Line Items.

When a user is viewing a Product, they have the option to add the product to their cart as a line item.

I am getting an error when I try to create a new line item instance. I could use some help understanding why I am getting this error and what I could do to fix it.

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), the button_to is where the line_item is being created

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


schema

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

Answer

Please check this line (last line in index.html.slim)

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

You'd need to change that to this :

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