Introducing the shopping cart
No real e-store without a shopping cart, so let’s implement one. First we get the shopping cart status and content to display them on the header of each page.
app/controllers/cart_controller.rb
cart = ShoppingCart.get()
Then display the status and content of the shopping cart in the header of the main layout template layout.erb
app/views/layouts/application.html.erb
<div class="cart box_1">
<h3> $<span id="cart_total" class="simpleCart_total" > <%= cart.total %> </span>
(<span id="cart_items_count" class="simpleCart_quantity"> <%= cart.count %> Items</span>)
<img src="/images/bag.png" alt="" />
</h3>
<p><a href="/cart" class="simpleCart_empty">Your cart</a></p>
</div>
Add items the shopping cart
We use AJAX to make a HTTP POST to our backend call with information about the item to add to the shopping cart,
view js/cart.js
file which contains the javascript AJAX code.
This is how to add the item to the cart, it is as simple as a single method call.
app/controllers/cart_controller.rb
def create
cart = ShoppingCart.add(LineItem.new(product: Product.new(id: params[:product]), quantity: params[:quantity]))
respond_to do |format|
msg = { total: cart.total, count: cart.count }
format.json { render :json => msg }
end
end
View the shopping cart
app/controllers/cart_controller.rb
def index
@cart = ShoppingCart.get()
end
In a previous step (Introducing the shopping cart), we learned how to get the shopping cart, and displayed its status, Now all what we need is to write the view template to display full content of the shopping cart.
app/views/cart/index.html.erb
<h2>MY SHOPPING CART </h2>
<% if cart.count <= 0 %>
<h1>No Items in your cart yet</h1>
<% else %>
<div class="cart-gd">
<% for item in cart.items %>
<div class="cart-header" id="<%= item.id %>" >
<a href="#" class="close1 deleteItem" data-item-id="<%= item.id %>"> </a>
<div class="cart-sec simpleCart_shelfItem">
<div class="cart-item cyc">
<img src="<%= item.product.mainPhoto.url %>" class="img-responsive" alt="" />
</div>
<div class="cart-item-info">
<h3><a href="#"> <%= item.product.title %> </a></h3>
<div class="delivery">
<p><span>Unit Price : $</span> <span><%= item.unitPrice %></span></p>
<div class="clearfix"></div>
<p><span>Quantity : $</span> <span><%= item.quantity %></span></p>
<div class="clearfix"></div>
<p><span>Total Price : $</span> <span><%= item.total %></span></p>
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<% end %>
<div style="margin-top: 50px; text-align: right;">
<a href="/orders/checkout" class="big_button">Checkout</a>
</div>
</div>
<% end %>
Delete items from the cart
Like the ‘add item’ operation, removing item is dome with AJAX POST to the '/cart/remove/:id'
path:
app/controllers/cart_controller.rb
def delete
cart = ShoppingCart.remove(params[:id])
respond_to do |format|
msg = { total: cart.total, count: cart.count }
format.json { render :json => msg }
end
end