ruby on rails - How can I get an id of an object that is not saved in db yet? -


i have method in cart model:

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 

in else statement use lineitemvariant.new(variant_id: variant_id, line_item_id: current_item.id) assign variant line_item. in case, can't save lineitemvariant, because line_item not exist yet, , can't use part of code: line_item_id: current_item.id. there solution id, or there easier option solve issue? ahead.

you can use accepts_nested_attributes_for

inside lineitemvariant model define

accepts_nested_attributes_for :line_item # or whatever relation towards item 

and change else statement

try convert object json when passing use 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 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -