LoginSignup
0
1

More than 1 year has passed since last update.

知らない人に勝手に出品した商品を編集させない!

Last updated at Posted at 2021-05-13

はじめに

現在フリマアプリを作成中です。

商品の出品者ではない人が編集できるURLを直接打ち込み、編集できるという問題を解決していきます。

想像してみて下さい。
自分が30,000円で出品した商品が勝手に1,000円に編集されて売れてしまった場合...

そんな事にならないように利用して下さるユーザーが安心して使えるように記述していきましょう!

現在のコントローラの状況

itemテーブルには出品された商品情報が入っています。
(名前・値段・商品説明・商品状態など)
編集できるeditアクションと更新ができるupdateアクションを見ていきます。

 def edit
    @item = Item.find(params[:id])   
 end

  def update
    if @item.update(item_params)
      redirect_to item_path
     else
      render :edit
    end

editアクションでは編集したいレコードを@itemに代入し、ビューに受け渡すことで編集画面で利用できるようにします。
findはデータベースからデータを取り出したり、検索したりするためのメソッドです。
idを取得して編集ページは/items/[:id]/editとなります。

今のままでは直接上記のURLを打ち込むと出品者ではない人が編集できてしまいます。

unless文とdeviseのヘルパーメソッド!

まずはunless文の紹介.
if文が条件式がtrueの時に実行したのに対し、unless文は条件式がfalseの時に実行する構文です。

そしてdeviseメソッド

current_user 
#deviseのヘルパーメソッドde"現在ログインしているユーザー"という意味

current_user == @item.user
#現在ログインしているユーザーは商品を出品ユーザーと同じという意味

この2つを用いて記述すると以下になります

 def edit
    @item = Item.find(params[:id]) 
    #もし、現在ログインしているユーザーは商品を出品ユーザーではなかった時、トップページに遷移する
    unless current_user == @item.user
      redirect_to root_path
    end
 end

  def update
    if @item.update(item_params)
      redirect_to item_path
     else
      render :edit
    end

このような記述になります。
もちろんこれはupdateアクションにも使うのでbefore_actionでまとめて記述するとより可読性が上がります。

before_action :contributor_confirmation, only: [:edit, :update]

def edit
end

  def update
    if @item.update(item_params)
      redirect_to item_path
     else
      render :edit
    end
  end

  private
def contributor_confirmation
    redirect_to root_path unless @item.user == current_user
end
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