簡體   English   中英

Rails錯誤:nil:NilClass的未定義方法`'

[英]Rails Error: undefined method ` ' for nil:NilClass

因此,由於我對Rails(和ruby)還很陌生,所以我仍在嘗試了解所有錯誤在哪里 我正在網上商店的購物車上工作。 用戶將獲得一個會話,其中將存儲他的購物車商品(在這種情況下為line_item.rb)。

問題:當我單擊一個項目時,它通過購物車方法add_product被添加到購物車中。 如果您再次單擊同一項目,而不是將同一項目添加兩次,則只需在該項目的數量屬性上加+1即可。 但是,當我第二次單擊它時,出現錯誤頁面,提示:

LineItemsController#create中的NoMethodError

undefined method `+' for nil:NilClass

這是我的cart.rb:

class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id)
    if current_item
      current_item.quantity += 1
      Rails.logger.debug(current_item.quantity)
    else
      current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
end

line_item的數量屬性為整數類型。 應該可以在上面加上整數,對嗎? 那就是我目前感到困惑的地方。

這是line_items_controller.rb中的“創建”方法:

  def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
@line_item.product = product

respond_to do |format|
  if @line_item.save
    format.html { redirect_to @line_item.cart,
      notice: 'Line item was successfully created.' }
    format.json { render json: @line_item,
      status: :created, location: @line_item }
  else
    format.html { render action: "new" }
    format.json { render json: @line_item.errors,
      status: :unprocessable_entity }
  end
end

結束

有任何想法嗎?

干杯

我認為這是因為current_item沒有任何數量。 可能沒有默認值。 您期望它為0,但實際上為nil

我設置了默認值,並確保該列不能為nil。 另外,您可以定義一個before_create方法,該方法將在保存之前將該值設置為0(如果為nil)。

解決此問題的另一種方法是確保您那里沒有零:

current_item.quantity = current_item.quantity.blank? ? 1 : current_item.quantity + 1

這表示current_item.quantity為null。 這可以是Integer,但在數據庫中存儲為null。 如果是這樣,您可以在遷移過程中默認設置一個值,或者在首次創建時可以將數量值設置為1。

暫無
暫無

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

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