0
0

ECサイト開発におけるdestroy_allの使用例

Last updated at Posted at 2024-05-28

はじめに

チーム開発が無事終了し、振り返りに躓いたところをアウトプットしています。
今回はECサイトを作成する中で、カートの中身を空にするために、destroy_allを使用しました。
検索しても良い記事が見当たらず…実装するのにものすごく時間がかかってしまったので使用例を紹介しようと思います。

destroy_allとは

Railsにはdestroy_allというActiveRecordのメソッドが用意されています。

ActiveRecordとは

Ruby on Rails で使用されるデザインパターンの一つです。
主な機能は下記です(まだまだあります)
①データベーステーブルとオブジェクトのマッピング
②CRUD操作のサポート
③バリデーション

今回は削除機能なので、②のCRUD操作サポートになります!

destroy_allは文字通り指定したレコードを全て削除することができるメソッドです。
例えば、データベース上の全てのItemを削除する場合は以下です。

Item.destroy_all

ログイン中のユーザーの全ての商品を削除したい場合は以下です。

current_customer.cart_items.destroy_all

モデル名などは調整してみてください。
cutomer→user? items→books?

では早速実際の記述内容に進みましょう!

モデル設定

商品(item)とカート内商品(cart_item)をリレーションします
item:cart_item = 1:N

ER図についてはこちら

model/item.rb
class Item < ApplicationRecord
   :
    has_many :cart_items
   :
    validates :price, presence: true

end
model/cart_item.rb
class CartItem < ApplicationRecord
    belongs_to :item
end

ルーティング

routes.rb
Rails.application.routes.draw do
  scope module: :public do
    resources :cart_items, only: [:index, :update, :destroy, :create] do
      collection do
        delete 'destroy_all'
      end
    end
end

このルーティングで、パスが「destroy_all_cart_items_path」になります。

コントローラー

cart_item.controller.rb
# 通常の削除機能
  def destroy
    cart_item = CartItem.find(params[:id])
    if cart_item.destroy
    flash[:notice] = "商品を削除しました。"
    redirect_to request.referer
    else
      flash.now[:alert] = "商品を削除できませんでした。"
      render 'index'
    end
  end

  # 全て削除
  def destroy_all
    if current_customer.cart_items.destroy_all
      flash[:notice] = "全ての商品を削除しました。"
      redirect_to request.referer
    else
      render 'index'
    end
  end

ifやflashはフラッシュメッセージを表示するための記述のため
省略しても機能に影響はございません。(省略Ver↓)

cart_item.controller.rb
def destroy_all
  current_customer.cart_items.destroy_all
  redirect_to request.referer
end

View

最後にView画面にカートを空にするボタンを表示させます

cart_item/index.html.erb
:
<%= link_to 'カートを空にする', destroy_all_cart_items_path , method: :delete , "data-confirm" => "カート内にある全ての商品が削除されます。\n本当に削除しますか?" , class: "btn btn-sm btn-danger" %>
:

スクリーンショット 2024-05-28 16.38.27.png

・link_to 'カートを空にする', destroy_all_cart_items_path , method: :delete
の記述により、Item全削除機能が実装され、

・"data-confirm" => "カート内にある全ての商品が削除されます。\n本当に削除しますか?"
の記述により、アラートポップアップが表示され、

・class: "btn btn-sm btn-danger"
の記述により、bootstrapを導入しているためレイアウトが整えられました

最後に

いかがでしたでしょうか?
以下の記事を参考にさせていただきました!
ありがとうございます!

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