2
0

More than 3 years have passed since last update.

【条件分岐】商品が売却されていたら処理をする方法

Last updated at Posted at 2021-08-09

今回覚えたことをメモします。
◇実装内容
商品購入機能後の条件分岐

◇結論◇
ビューファイルに、「item.purchase」と記述をすると「商品に紐づく購入履歴」という形で処理をしてくれた。
そこにif文を加えて「もし、その商品を購入していたら〜処理〜」とうい記述ができた。
※モデル名で名前は変わる。

↓は「もし、その商品を購入していたらSold Out!!を表示させる」

index.html.erb
  <% if item.purchase %>
     <div class='sold-out'>
       <span>Sold Out!!</span>
     </div>
   <% end %>

◇前提◇
2つはアソシエーションが組まれている
商品情報:itemモデル
購入履歴:purchaseモデル
 カラム:user_id
    :item_id

◇別の例◇
↓コントローラーに記述。before_actionメゾットで編集ページは商品が購入されたら、root_pathへ戻る形になる。

items_controller.rb
before_action :item_purchase ,only: :edit

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

 def  item_purchase
  @item = Item.find(params[:id])
   if @item.purchase
    redirect_to root_path
   end
 end

本日は以上です。

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