簡體   English   中英

錯誤未定義方法 `+' for nil:NilClass // Ruby on Rails

[英]Error undefined method `+' for nil:NilClass // Ruby on Rails

我在這里遇到了一些問題,我建立了一個簡單的市場,但是當在購物車中添加產品時,應該將 line_item(通過 ID 表示產品)添加到購物車中。 相反,沒有創建 line_item 並且我彈出了這個錯誤。

我檢查了模型之間的關系,再次做了路線,檢查了視圖和 forms。 如果我使用@line_item.save 而不是@line_item.save。 我可以看到我的購物車視圖,但沒有創建 line_item...

我在這里想念什么? 謝謝

  create_table "line_items", force: :cascade do |t|
    t.integer "quantity"
    t.integer "product_id"
    t.integer "cart_id"
    t.integer "order_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
class LineItem < ApplicationRecord
  belongs_to :product
  belongs_to :cart
  belongs_to :order, optional: true

  def total_price
    self.quantity * self.product.price
  end
end
class LineItemsController < ApplicationController
  def create
    # Find associated product and current cart
    chosen_product = Product.find(params[:product_id])
    current_cart = @current_cart

    # If cart already has this product then find the relevant line_item and iterate quantity otherwise create a new line_item for this product
    if current_cart.products.include?(chosen_product)
      # Find the line_item with the chosen_product
      @line_item = current_cart.line_items.find_by(product_id: chosen_product)
      # Iterate the line_item's quantity by one

      @line_item.quantity += 1

    else
      @line_item = LineItem.new
      @line_item.cart = current_cart
      @line_item.product = chosen_product

    end

    # Save and redirect to cart show path
    @line_item.save!
    redirect_to cart_path(current_cart)

  end

  def add_quantity
    @line_item = LineItem.find(params[:id])
    @line_item.quantity += 1
    @line_item.save
    redirect_to cart_path(@current_cart)
  end

  def reduce_quantity
    @line_item = LineItem.find(params[:id])
    if @line_item.quantity > 1
      @line_item.quantity -= 1
    end
    @line_item.save
    redirect_to cart_path(@current_cart)
  end

  def destroy
    @line_item = LineItem.find(params[:id])
    @line_item.destroy
    redirect_to cart_path(@current_cart)
  end

  private

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

end
Rails.application.routes.draw do
  devise_for :users

root 'products#index'

get 'carts/:id' => "carts#show", as: "cart"
delete 'carts/:id' => "carts#destroy"

post 'line_items/:id/add' => "line_items#add_quantity", as: "line_item_add"
post 'line_items/:id/reduce' => "line_items#reduce_quantity", as: "line_item_reduce"
post 'line_items' => "line_items#create"
get 'line_items/:id' => "line_items#show", as: "line_item"
delete 'line_items/:id' => "line_items#destroy"

resources :products
resources :orders

end

您的quantity為零,這就是您收到錯誤的原因。 也許在遷移中為它添加一個默認值,如下所示:

t.quantity, type: :integer, default: 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2025 STACKOOM.COM