簡體   English   中英

滑軌。 購物車中相同訂單項的關聯

[英]Rails. Association of the same line items in the cart

將相同的訂單項添加到購物車時,我需要將其關聯。 現在,每個提交表單后我都有一個新的訂單項。 我嘗試使用訂單項控制器中的add_product修復它:

訂單項控制器:

def create
  @cart = current_cart
  @line_item = @cart.add_product(@product.id)    
end

推車型號

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 += line_item.quantity.to_i
    else
        current_item = line_items.build(product_id: product_id)
    end
    current_item
end

顯示產品頁面中的訂單項表單部分呈現:

= form_for (@line_item) , remote: true do |f| 
    div class="input-group"
        = f.number_field :quantity, value: 1, class: "form-control", min: 1 
        div class="input-group-btn"
                = f.hidden_field :product_id, value: @product.id 
                = f.submit "Add to Cart"

但是提交表單后出現錯誤:“ NoMethodError(nil:NilClass的未定義方法'id'):”

如何將@ product.id從表單轉移到控制器?

UPD在line_item控制器中添加@product

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

您必須通過參數中的product_id在控制器的create動作(或before_action)中找到@product。 就像是:

@product = Product.find(params[:line_item][:product_id])

(雖然不是很漂亮)

暫無
暫無

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

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