LoginSignup
28
41

More than 3 years have passed since last update.

[Rails]ECサイトのカート機能

Posted at

はじめに

Ruby on RailsでECサイトを作成しました。
その際、カート機能の実装でかなり時間を費やしたので、やり方を記載してみようと思います。

前提条件

カート機能を持たせるためには、DBにテーブルが必要になってきます。
他テーブルとの関連付けなどについては以下の記事にて記載しております。
[Rails] ECサイトのDB設計

カート機能の根幹の部分

ここでは、セッションを作成します。

セッションについては、以下の記事がわかりやすいです。
【Rails】Sessionの使い方について

要は、データを保持してくれる仕組みですね。
で、このカートのセッション作成は以下のようにコーディングしました。

# application_controller.rb
class ApplicationController < ActionController::Base

private
  #セッションの作成
  def current_cart
    # セッションから取得したcart_idを元にCartテーブルからCart情報を取得
    current_cart = Cart.find_by(id: session[:cart_id])
    # Cart情報が存在しない場合、@current_cartを作成
    current_cart = Cart.create unless current_cart
    # 取得したCart情報よりIDを取得し、セッションに設定
    session[:cart_id] = current_cart.id
    # Cart情報を返却
    current_cart
  end
end

ここで定義した"current_cart"を他のcontrollerでも使用していきます。

カートに商品を入れていく

ここからは先ほど作成したメソッドをcarts_controllerで使用していきます。

class CartsController < ApplicationController
  before_action :set_line_item, only: [:add_item, :destroy]
  before_action :set_user
  before_action :set_cart

  def show
    @line_items = @cart.line_items
  end

  def add_item
    @line_item = @cart.line_items.build(product_id: params[:product_id]) if @line_item.blank?
    @line_item.quantity += params[:quantity].to_i
    if @line_item.save
      redirect_to current_cart
    else
      redirect_to controller: "products", action: "show"
    end
  end

  def destroy
    @cart.destroy
    redirect_to current_cart
  end

  private
  def set_user
    @user = current_user
  end

  def set_line_item
    @line_item = current_cart.line_items.find_by(product_id: params[:product_id])
  end

  def set_cart
    @cart = current_cart
  end
end

add_itemアクションですが、商品詳細ページに"カートに入れる"ボタンを設置しており、POSTのHTTPメソッドでカートに商品の追加をしています。

@line_item = @cart.line_items.build(product_id: params[:product_id]) if @line_item.blank?

上記ですが、buildメソッドを使用しています。
buildはnewのエイリアスですが、慣例として関連付けされたモデルのオブジェクトを生成する際には、buildを使い、それ以外でnewを用いるという使い分けがされているらしいです。

今回はcartが親、line_itemが子の関係なので、line_itemモデルのオブジェクトを生成したいためにbuildを使用したということです。(間違ってたらごめんなさい)

基本的にここまででカートとして機能しているかと思います。

因みに

solidusというgemを使用すれば、秒でECサイトを作成できます。

参考記事↓
Spreeの後継ECシステム、Solidusのインストールメモ

試しに使ってみましたが、カスタマイズがだるそうです。
目的によっては使ってみるのもアリかもですね。

28
41
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
28
41