4
6

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 5 years have passed since last update.

Railsのトランザクションと例外処理

Last updated at Posted at 2019-10-11

Railsのトランザクションと例外処理がよく分からなかったので、調べました。

app/controllers/user_controller.rb

def create
  ActiveRecode::Base.transaction do
    # createではなく、create!にすると保存できなかったときに例外が発生します。
    @user = User.create!(user_params)
   
  rescue => e 
  # バリデーションエラーだけ拾いたい場合は次の行
  # (ActiveRecord:RecodeInvalid => e) 
    # error処理
  end

end

rescueはphpでいうとexceptionみたいな感じでした。

参考サイト

rails save! create! update!のバリデーション例外を捕捉する - Qiita

【Rails】例外処理の書き方(begin, rescue, raise,retry, ensure) - Qiita

rubyの例外についてまとめてみた - Qiita

ActiveRecord::Base.transactionで囲うタイミング - Qiita

4
6
1

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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?