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 @@