bookstore/app/controllers/books_controller.rb
2021-03-22 02:25:17 +01:00

48 lines
1,000 B
Ruby

class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :add_to_cart]
before_action :ensure_admin, only: [:edit, :update]
def index
if current_user&.admin?
books = Book.all
else
books = Book.published
end
@books = books.map { |book| BooksPresenter.new(book) }
end
def show
end
def edit
end
def update
if @book.update(book_params)
redirect_to '/books'
end
end
def add_to_cart
@book = Book.find(params[:id])
current_user.books << @book
@book.decrement!(:quantity)
redirect_to '/books', notice: 'Book added to your cart'
end
def shopping_cart
@books = current_user.books.map { |book| BooksPresenter.new(book) }
end
private
def set_book
@book = BooksPresenter.new(Book.find(params[:id]))
end
def book_params
result = params.require(:book).permit(:title, :price, :published)
result['price'] = result['price'].to_d * 100
result
end
end