Ruby on rails rails中的高级查询

Ruby on rails rails中的高级查询,ruby-on-rails,ruby-on-rails-3,postgresql-9.1,Ruby On Rails,Ruby On Rails 3,Postgresql 9.1,我有以下型号: class Author < ActiveRecord::Base has_many :books end class Book < ActiveRecord::Base belongs_to :author end 如何创建一个查询来获取5本书,每本书都来自不同的作者 另一个条件是,如果我的作者少于5位,我仍然应该得到5本书,每个作者一本,其余的书可以来自这些作者中的任何一位。让我们先随机获得5位作者: authors = Author.all.orde

我有以下型号:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end
如何创建一个查询来获取5本书,每本书都来自不同的作者


另一个条件是,如果我的作者少于5位,我仍然应该得到5本书,每个作者一本,其余的书可以来自这些作者中的任何一位。

让我们先随机获得5位作者:

authors = Author.all.order('random()').limit(5)
现在让我们试着为每一本买一本书

chosen_books = []
authors.each do |author|
  chosen_books << author.books.order('random()').first
end
现在,我们可以检查我们是否仍然是短小的书

if chosen_books.size < 5
  already_chosen_book_ids = chosen_books.map(&:id)
  limit = 5 - chosen_books.size
  extra_books = Book.where(author: authors).where('id NOT IN (?)', already_chosen_book_ids).order('random()').limit(limit)
  chosen_books = chosen_books.concat(extra_books.to_a)
end

请发布你迄今为止所尝试过的。嗨,乔希。我有一个想法的基础上,但这只是解决的情况下,有超过5名作者