LoginSignup
1
0

More than 3 years have passed since last update.

例外処理

Posted at

普通の削除処理


  def destroy
    hoge = Hoge.find(params[:id])
    hoge.destroy
    redirect_to root_path
  end

削除機能に例外処理を実装

  def destroy
    begin 
      # 例外が起こるかもしれないコード
      hoge = Hoge.find(10)
      hoge.destroy
    rescue => error
      # 例外が発生した時のコード
      flash[:notice] = "削除に失敗しました"
    ensure
      # 例外が起こっても起こらなくても実行したい時のコード
      redirect_to root_path
    end
  end

更新機能に例外処理を実装する場合

  • begin~endは省略できる。下記は省略形。
  • 送られてきたIDが存在しない場合と、バリデーションに引っかかった場合とそれぞれ別にrescueを記載する。
  def update
    @post = Post.find(params[:id])
    @post.update!(post_params)
    redirect_to root_path
  rescue ActiveRecord::RecordNotFound => e
    flash[:notice] = "指定したIDが見つかりませんでした"
    redirect_to root_path
  rescue ActiveRecord::RecordInvalid => e
    render :edit
  end

こんな書き方でも大丈夫そう??


  def update
    begin
      @post = Post.find(params[:id])
      if @post.update(post_params)
        redirect_to root_path
      else
        render :edit
      end
    rescue 
      flash[:notice] = "IDが見つかりません"
      redirect_to root_path
    end
  end
1
0
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
1
0