Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions app/controllers/api/shelvings_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def index

def create
shelving = @bookshelf.shelvings.new(shelving_params)
Bookshelf.change_count('inc', @bookshelf)
Bookshelves::BookshelfShelvingCounter.new('inc', @bookshelf).change_count
if shelving.save
render json: shelving
else
Expand All @@ -31,8 +31,9 @@ def update

def destroy
shelving = Shelving.find(params[:id].to_i)
bookshelf = Bookshelves::BookshelfShelvingCounter.new('dec', @bookshelf).change_count
if shelving.destroy
render json: Bookshelf.change_count('dec', @bookshelf)
render json: bookshelf
else
render json: { errors: shelf.errors.full_messages.join(', ')}, status: 422
end
Expand Down
17 changes: 4 additions & 13 deletions app/models/book.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,9 @@ def self.check_if_duplicate(book_params)

def self.only_with_ratings
distinct.select('books.item, r.book_id, COUNT(r.book_id) AS review_count, AVG(r.value)')
.joins('INNER JOIN ratings AS r ON books.id = r.book_id')
.group('r.book_id, books.item')
.order('avg DESC')
.limit('20')
end

def self.change_count(action, bookshelf)
case action
when 'inc'
bookshelf.update(book_count: bookshelf.book_count += 1)
when 'dec'
bookshelf.update(book_count: bookshelf.book_count -= 1)
end
.joins('INNER JOIN ratings AS r ON books.id = r.book_id')
.group('r.book_id, books.item')
.order('avg DESC')
.limit('20')
end
end
20 changes: 20 additions & 0 deletions app/services/bookshelves/bookshelf_shelving_counter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module Bookshelves
class BookshelfShelvingCounter
def initialize(action, bookshelf)
@action = action
@bookshelf = bookshelf
end

attr_accessor :action, :bookshelf

def change_count
case action
when 'inc'
bookshelf.update(book_count: bookshelf.book_count += 1)
when 'dec'
bookshelf.update(book_count: bookshelf.book_count -= 1)
end
bookshelf
end
end
end