diff --git a/app/controllers/api/shelvings_controller.rb b/app/controllers/api/shelvings_controller.rb index e16cfc7..6ece25d 100644 --- a/app/controllers/api/shelvings_controller.rb +++ b/app/controllers/api/shelvings_controller.rb @@ -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 @@ -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 diff --git a/app/models/book.rb b/app/models/book.rb index e6f8479..0f6a20e 100644 --- a/app/models/book.rb +++ b/app/models/book.rb @@ -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 diff --git a/app/services/bookshelves/bookshelf_shelving_counter.rb b/app/services/bookshelves/bookshelf_shelving_counter.rb new file mode 100644 index 0000000..99327fb --- /dev/null +++ b/app/services/bookshelves/bookshelf_shelving_counter.rb @@ -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