LoginSignup
0
0

More than 3 years have passed since last update.

本日、商品削除機能の実装が完了した。苦労したのは以下のコード。  

 def destroy
    if current_user.id == @item.user_id
      redirect_to root_path if @item.destroy
    else
      render :show
    end
 end  

コードを読み解いていくと

(1)現在ログインしているユーザー(current_user.id)と
   商品を出品しているユーザーが一致しているかどうか判定。

(2)(1)の条件式が正しくて(true)
   出品した商品が削除されたのなら
   トップページに戻る。

(3)もし商品が削除されなければ商品詳細ページに遷移するという流れになる。

最初は以下のようにコードを書いていた。  

def destroy
    if @item.destroy
      redirect_to root_path if current_user.id == @item.user_id
    else
      render :show
    end
 end

上記のように書くと商品が削除された後に
現在のユーザーと出品者が一致しているのか判定される。

エラーが出る訳ではないものの
アプリが予期しない動きをする可能性がある。

そのため修正を行なった。

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