LoginSignup
19

More than 5 years have passed since last update.

rails4系でcreate or updateをするアレ

Posted at

実はデフォルトのメソッドではなかったりします。

where.(id: 100).first_or_createとかはあるんですけどね。。
きっとRails5が出る頃には実装されているのでしょう。

これがあるとバッチで請求情報とか作る時にいいですよね!
請求情報なんて様々な事情で何度も作り直しすることもありますし(白目)

cutoff_date = Time.now.end_of_month
User.all.each do |user|
  invoice = Invoice.find_or_initialize_by(
    user_id: user.id,
    cutoff_date: cutoff_date.strftime('%Y-%m-%d'),
  )
  invoice.user_id = user.id
  invoice.price = 10000
  invoice.cutoff_date = cutoff_date.strftime('%Y-%m-%d')
  invoice.save!
end

これで何回バッチを回しても安心です(爆)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19