如何获取未在db中保存的对象的id?

时间:2017-09-11 08:11:59

标签: ruby-on-rails database model

我的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 声明中,我使用elseLineItemvariant.new(variant_id: variant_id, line_item_id: current_item.id)分配给variant。但在这种情况下,我无法保存line_item,因为LineItemVariant尚不存在,我无法使用这部分代码:line_item。是否有任何解决方案来获取I​​D,或者有一些更容易的选择来解决这个问题?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用accepts_nested_attributes_for

LineItemVariant模型中定义

accepts_nested_attributes_for :line_item # or whatever relation is towards this item

然后更改你的其他声明

尝试使用to_json

将对象转换为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