p = product.dup.update_attributes(name: "The latest thing")
上記のコードはproduct、1 つの属性を変更して、オブジェクトの複製を作成 (および保存) します。
新しく作成されたレコードの ID を取得するにはどうすればよいですか? 変数pは を返すだけtrueです。
p = product.dup.update_attributes(name: "The latest thing")
上記のコードはproduct、1 つの属性を変更して、オブジェクトの複製を作成 (および保存) します。
新しく作成されたレコードの 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_attributestruefalse
p = product.dup
p.update_attributes(name: "The latest thing")
p.id