cart summary and refactoring

This commit is contained in:
Karol Selak 2021-03-22 02:49:05 +01:00
parent df7585c5e1
commit c63c6bc448
4 changed files with 20 additions and 8 deletions

View file

@ -25,6 +25,8 @@ class BooksController < ApplicationController
def add_to_cart
@book = Book.find(params[:id])
return unless @book.quantity.positive?
current_user.books << @book
@book.decrement!(:quantity)
redirect_to '/books', notice: 'Book added to your cart'

View file

@ -1,2 +1,8 @@
module BooksHelper
def cart_summary
number_to_currency(@books.map{ |b| b.price }.reduce(:+))
end
def can_book_be_added?(book)
logged_in? && book.quantity.positive? && !current_user.books.exists?(book.id)
end
end

View file

@ -1,9 +1,9 @@
<div class='container'>
<div class='row'>
<div class='col s2'>Title</div>
<div class='col s3'>Authors</div>
<div class='col s1'>Price</div>
<div class='col s3'>Quantity</div>
<h6 class='col s2'>Title</h6>
<h6 class='col s3'>Authors</h6>
<h6 class='col s1'>Price</h6>
<h6 class='col s3'>Quantity</h6>
</div>
<% @books.each do |book| %>
@ -24,7 +24,7 @@
<%= book.quantity %>
</div>
<div class='col s2'>
<% if logged_in? && book.quantity.positive? && !current_user.books.exists?(book.id) %>
<% if can_book_be_added?(book) %>
<%= link_to 'Add', "book/#{book.id}/add_to_cart", method: :post, class: "btn" %>
<% end %>
</div>

View file

@ -1,8 +1,8 @@
<div class='container'>
<div class='row'>
<div class='col s2'>Title</div>
<div class='col s3'>Authors</div>
<div class='col s1'>Price</div>
<h6 class='col s2'>Title</h6>
<h6 class='col s3'>Authors</h6>
<h6 class='col s1'>Price</h6>
</div>
<% @books.each do |book| %>
<div class='row'>
@ -19,4 +19,8 @@
</div>
</div>
<% end %>
<div class='row'>
<div class='col s5'><strong>Summary</strong></div>
<div class='col s1'><%= cart_summary %></div>
</div>
</div>