0

I have three models:

  • Book [belongs_to :author]
  • Author [belongs_to :publisher, has_many :books]
  • Publisher [has_many :authors]

I want to know how many Books have every Publisher, grouped by Publisher and ordered by Publishers with most Books. I need to get a list with a single query, where I can get something like:

  • Publisher ABC: 3800 books
  • Publisher XYZ: 1922 books
  • Publisher JKL: 192 books
  • and so on

Books belongs to Author but not to Publisher directly —complicated to explain why. Is there a easy way to achieve this?

4

2 回答 2

0

Use has_many through to define a relation between publisher and books like this

# publisher.rb

has_many :books, :through => :authors

Then you get the ordered count like this

records =  Publisher.joins(:books).
                     group("publishers.id").
                     select("publishers.*, COUNT(*) AS books_count").
                     order("books_count DESC")
# => access book count as record.book_count

If you need to access the books count for publisher often then look into adding a column called books_countin publishers table (to improve performance). You can update it using counter cache

于 2013-10-16T11:02:39.477 回答
0

This should work:

counts = Publisher.joins(:authors => :books).
                   select('publishers.id, count(books.id) as number').
                   group('publishers.id')
# count[0] is now a Publisher object; and counts[0].number is the count of books they own
于 2013-10-16T11:09:26.583 回答