xengineer’s diary

結果、メモ的な内容になっています。

複数attributeを既存のARにセットしたいとき

表題のことをやるときに何回か思い出せなかったのでメモ。

このサイトみたほうが、圧倒的に詳しいので、次に忘れたときは、

一旦この記事にきて、このサイトを見にいくんだろうな・・・

ActiveRecord の attribute 更新方法まとめ - Qiita
ActiveRecord::AttributeAssignment

例えば、こんなことはしたくないわけです。(コードはてきとうです)

test = Test.find(params[:test])
test_hash = { testa: "testa", testb: "testb", testc: "testc" }
test.a = test_hash[:testa]
test.b = test_hash[:testb]
test.c = test_hash[:testc]

それなら、assign_attributesを使うのがいいよ、とのことです。

test = Test.find(params[:test])
test_hash = { testa: "testa", testb: "testb", testc: "testc" }
test.assign_attributes(test_hash)

僕は、こんなときに使おうとして思い出せなくて、を繰り返しています。

test = foo.bars.find_or_initialize_by(foobar)

if test.new_record?
  some code
else
  test.assign_attibutes(test_hash)
  test.save! if test.changed?
end

おわり。