I created an EC site with Ruby on Rails. At that time, I spent a lot of time implementing the cart function, so I will describe how to do it.
In order to have the cart function, a table is required in the DB. The association with other tables is described in the following article. [Rails] DB design for EC site
Here we will create a session.
For sessions, the following articles are easy to understand. [Rails] How to use Session
In short, it's a mechanism that retains data. So, I coded the session creation for this cart as follows:
# application_controller.rb
class ApplicationController < ActionController::Base
private
#Creating a session
def current_cart
#Cart obtained from session_Get Cart information from Cart table based on id
current_cart = Cart.find_by(id: session[:cart_id])
#If Cart information does not exist@current_Create cart
current_cart = Cart.create unless current_cart
#Obtain the ID from the obtained Cart information and set it in the session
session[:cart_id] = current_cart.id
#Return Cart information
current_cart
end
end
The "current_cart" defined here will be used for other controllers as well.
From here, we will use the method created earlier in 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
Regarding the add_item action, the "Add to cart" button is installed on the product detail page, and the product is added to the cart using the HTTP method of POST.
@line_item = @cart.line_items.build(product_id: params[:product_id]) if @line_item.blank?
Above, I'm using the build method. build is an alias of new, but it seems that when creating an object of the associated model by convention, build is used and new is used in other cases.
This time, cart is the parent and line_item is the child, so we used build to create an object for the line_item model. (Excuse me if I am wrong)
Basically, I think that it is functioning as a cart so far.
You can create an EC site in seconds by using a gem called solidus.
Reference article ↓ Installation memo of Solidus, the successor EC system of Spree
I tried using it, but it seems that customization is slow. It may be an ant to try it depending on the purpose.
Recommended Posts