Ruby on rails ActiveRecord复杂查询

Ruby on rails ActiveRecord复杂查询,ruby-on-rails,activerecord,rails-activerecord,Ruby On Rails,Activerecord,Rails Activerecord,我找不到最畅销的书。我有以下型号: 书 classbook

我找不到最畅销的书。我有以下型号: 书

classbook
图书类别

class BooksCategory < ApplicationRecord
  belongs_to :category
  belongs_to :book
end
class-BooksCategory
类别

class Category < ApplicationRecord
  has_and_belongs_to_many :books
end
类别
订单项

class OrderItem < ApplicationRecord
  belongs_to :order
  belongs_to :book
end
class OrderItem
秩序

class Order < ApplicationRecord
  has_many :order_items, dependent: :destroy
  has_many :books, through: :order_items
end
类顺序
所以我需要从每个类别中找出最畅销的书。当订单状态为2或3时,书籍被视为已售出。我编写了下一个代码:

  def best_sellers
    books_ids = []

    Category.all.each do |category|
      temp_hash = OrderItem.joins(book: :books_categories)
        .where(books: { books_categories: { category: category } })
        .joins(:order).where(orders: { status: [2, 3] })
        .group(:book_id).sum(:quantity)

      books_ids << temp_hash.key(temp_hash.values.max)
    end

    Book.where(id: books_ids)
  end
def畅销书
书籍\u id=[]
Category.all.each do | Category|
temp\u hash=OrderItem.join(book::books\u类别)
.where(图书:{books\u categories:{category:category}})
.joins(:order).where(orders:{status:[2,3]})
.组(:账簿id).总和(:数量)
图书标识
  def best_sellers
    books_ids = []

    Category.all.each do |category|
      temp_hash = OrderItem.joins(book: :books_categories)
        .where(books: { books_categories: { category: category } })
        .joins(:order).where(orders: { status: [2, 3] })
        .group(:book_id).sum(:quantity)

      books_ids << temp_hash.key(temp_hash.values.max)
    end

    Book.where(id: books_ids)
  end