shopping cart
This commit is contained in:
parent
733870ce96
commit
df7585c5e1
11 changed files with 79 additions and 11 deletions
|
@ -1,5 +1,5 @@
|
|||
class BooksController < ApplicationController
|
||||
before_action :set_book, only: [:show, :edit, :update]
|
||||
before_action :set_book, only: [:show, :edit, :update, :add_to_cart]
|
||||
before_action :ensure_admin, only: [:edit, :update]
|
||||
|
||||
def index
|
||||
|
@ -23,6 +23,17 @@ class BooksController < ApplicationController
|
|||
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
|
||||
|
|
|
@ -15,4 +15,9 @@ class ApplicationRecord < ActiveRecord::Base
|
|||
AuditRecord.create(model: self.class, action: 'create', params: result.to_json)
|
||||
result
|
||||
end
|
||||
def decrement!(*args)
|
||||
result = super(*args)
|
||||
AuditRecord.create(model: self.class, action: 'decrement!', params: self.to_json)
|
||||
result
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
class User < ApplicationRecord
|
||||
has_and_belongs_to_many :books
|
||||
|
||||
has_secure_password
|
||||
has_secure_password :recovery_password, validations: false
|
||||
enum role: [:customer, :admin], _default: :customer
|
||||
|
|
|
@ -24,8 +24,8 @@
|
|||
<%= book.quantity %>
|
||||
</div>
|
||||
<div class='col s2'>
|
||||
<% if logged_in? && book.quantity.positive? %>
|
||||
<%= link_to 'Add', edit_book_path(book), class: "btn" %>
|
||||
<% if logged_in? && book.quantity.positive? && !current_user.books.exists?(book.id) %>
|
||||
<%= link_to 'Add', "book/#{book.id}/add_to_cart", method: :post, class: "btn" %>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
|
|
22
app/views/books/shopping_cart.erb
Normal file
22
app/views/books/shopping_cart.erb
Normal file
|
@ -0,0 +1,22 @@
|
|||
<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>
|
||||
<% @books.each do |book| %>
|
||||
<div class='row'>
|
||||
<div class='col s2'>
|
||||
<%= link_to book.title, book %>
|
||||
</div>
|
||||
|
||||
<div class='col s3'>
|
||||
<%= book.authors %>
|
||||
</div>
|
||||
|
||||
<div class='col s1'>
|
||||
<%= book.price_with_currency %>
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
|
@ -32,7 +32,7 @@
|
|||
<% end %>
|
||||
<% if logged_in? %>
|
||||
<div class='col s2'>
|
||||
<%= link_to 'Shopping cart', '/authors', method: :get%>
|
||||
<%= link_to 'Shopping cart', '/shopping_cart', method: :get%>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue