bookstore/app/controllers/books_controller.rb

51 lines
1 KiB
Ruby
Raw Normal View History

2021-03-19 17:31:38 +02:00
class BooksController < ApplicationController
2021-03-22 02:25:17 +01:00
before_action :set_book, only: [:show, :edit, :update, :add_to_cart]
2021-03-21 20:30:25 +01:00
before_action :ensure_admin, only: [:edit, :update]
2021-03-19 17:31:38 +02:00
def index
2021-03-22 01:24:13 +01:00
if current_user&.admin?
2021-03-21 20:30:25 +01:00
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
2021-03-22 02:25:17 +01:00
def add_to_cart
@book = Book.find(params[:id])
2021-03-22 02:49:05 +01:00
return unless @book.quantity.positive?
2021-03-22 02:25:17 +01:00
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
2021-03-21 20:30:25 +01:00
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
2021-03-19 17:31:38 +02:00
end
end