2017-09-11 76 views
0

我在Cart模型的方法:如何獲取未保存在數據庫中的對象的ID?

def add_product_with_variant(product_id, variant_id) 
    current_item = line_items.find_by(product_id: product_id) 
    if current_item 
    current_item.amount += 1 
    line_item_variant = LineItemVariant.new(variant_id: variant_id, line_item_id: current_item.id) 
    line_item_variant.save 
    else 
    current_item = line_items.build(product_id: product_id) 
    line_item_variant = LineItemVariant.new(variant_id: variant_id, line_item_id: current_item.id) 
    line_item_variant.save! 
    end 
end 

else發言中,我使用LineItemvariant.new(variant_id: variant_id, line_item_id: current_item.id)variant分配給line_item。但在這種情況下,我不能保存LineItemVariant,因爲line_item尚不存在,我不能使用這部分代碼:line_item_id: current_item.id。有沒有解決方案來獲得ID,或者有更簡單的方法來解決這個問題?謝謝你。

+1

創建'current_it em'而不是'build',然後使用它的'id'。 – Pavan

回答

0

您可以使用accepts_nested_attributes_for

裏面你LineItemVariant模型定義

accepts_nested_attributes_for :line_item # or whatever relation is towards this item 

,然後改變你的else語句

嘗試對象轉換成JSON傳遞時使用to_json

def add_product_with_variant(product_id, variant_id) 
    current_item = line_items.find_by(product_id: product_id) 
    if current_item 
    current_item.amount += 1 
    line_item_variant = LineItemVariant.new(variant_id: variant_id, line_item_id: current_item.id) 
    line_item_variant.save 
    else 
    current_item = line_items.build(product_id: product_id) 
    line_item_variant = LineItemVariant.new(variant_id: variant_id, line_item: current_item.to_json) 
    line_item_variant.save! 
end 
+0

它給出了一個錯誤:'驗證失敗:行項目必須存在' –

+0

嘗試將傳遞對象作爲json – Nermin

+0

新'line_item'的'id'仍然是'nil' –

相關問題