繁体   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