0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rails saveとsave!の違い

Posted at

#はじめに
rails学習中にXXX.save!と記載されたコードを確認し、
普段書いているXXX.saveとの違いが気になったためまとめました。

#結論
XXX.save:通常のメソッド 成功時⇒保存 失敗時⇒falseを返す
XXX.save!:破壊的メソッド 成功時⇒保存 失敗時⇒例外を返す

例えばOrderモデルのtotal_priceに0円より大きい値のみ許可を与えている場合
以下の挙動を示す

[3] pry(main)> order=Order.new
   (0.6ms)  SELECT sqlite_version(*)
  TRANSACTION (0.0ms)  begin transaction
=> #<Order:0x000000012ee09aa0 id: nil, total_price: 0, created_at: nil, updated_at: nil>
[4] pry(main)> order.save
=> false
[5] pry(main)> order.save!
ActiveRecord::RecordInvalid: Validation failed: Total price must be greater than 0

#save!のメリット

  • 失敗時にエラーが発生し、原因が追求しやすい
  • 例外が発生することで、処理が止まる
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?