我的Requirements
• Python 3.3
• GTK+ 3.14
• GLib 2.36
• PyGObject 3.14
• GtkSourceView 3.14
• pycairo
模型中有一个方法:
Cart
在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
。是否有任何解决方案来获取ID,或者有一些更容易的选择来解决这个问题?谢谢。
答案 0 :(得分:0)
您可以使用accepts_nested_attributes_for
在LineItemVariant
模型中定义
accepts_nested_attributes_for :line_item # or whatever relation is towards this item
然后更改你的其他声明
尝试使用to_json
将对象转换为jsondef 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