p = product.dup.update_attributes(name: "The latest thing")
上面的代码创建(并保存)对象的副本product,其中一个属性已更改。
如何检索新创建记录的 id?变量p只返回true。
p = product.dup.update_attributes(name: "The latest thing")
上面的代码创建(并保存)对象的副本product,其中一个属性已更改。
如何检索新创建记录的 id?变量p只返回true。
这里的问题是 p 等于返回 update_attributes (如果更新成功则为 true,否则为 false)
你应该做这个:
product_copy = product.dup # copies the product into a new one, stocked in variable product_copy
product_copy.update_attributes(name: "The latest thing")
product_copy # => your Product object
替代:
product_copy = product.dup
product_copy.name = "The latest thing"
product_copy.save
它返回true是因为update_attributes是最后一个被评估的方法。所以p被分配了update_attributes方法的值,它要么是true要么false。
p = product.dup
p.update_attributes(name: "The latest thing")
p.id