From c63c6bc448b18b57e318848c5ae8fbb460852d45 Mon Sep 17 00:00:00 2001 From: Karol Selak Date: Mon, 22 Mar 2021 02:49:05 +0100 Subject: [PATCH] cart summary and refactoring --- app/controllers/books_controller.rb | 2 ++ app/helpers/books_helper.rb | 6 ++++++ app/views/books/index.html.erb | 10 +++++----- app/views/books/shopping_cart.erb | 10 +++++++--- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb index 29b4e35..190b6da 100644 --- a/app/controllers/books_controller.rb +++ b/app/controllers/books_controller.rb @@ -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' diff --git a/app/helpers/books_helper.rb b/app/helpers/books_helper.rb index 4b9311e..00d4182 100644 --- a/app/helpers/books_helper.rb +++ b/app/helpers/books_helper.rb @@ -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 diff --git a/app/views/books/index.html.erb b/app/views/books/index.html.erb index d13fc32..412346b 100644 --- a/app/views/books/index.html.erb +++ b/app/views/books/index.html.erb @@ -1,9 +1,9 @@
-
Title
-
Authors
-
Price
-
Quantity
+
Title
+
Authors
+
Price
+
Quantity
<% @books.each do |book| %> @@ -24,7 +24,7 @@ <%= book.quantity %>
- <% 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 %>
diff --git a/app/views/books/shopping_cart.erb b/app/views/books/shopping_cart.erb index 8b6ee48..39f6cdf 100644 --- a/app/views/books/shopping_cart.erb +++ b/app/views/books/shopping_cart.erb @@ -1,8 +1,8 @@
-
Title
-
Authors
-
Price
+
Title
+
Authors
+
Price
<% @books.each do |book| %>
@@ -19,4 +19,8 @@
<% end %> +
+
Summary
+
<%= cart_summary %>
+