【问题标题】:Advance query in railsRails 中的高级查询
【发布时间】:2013-11-27 04:05:53
【问题描述】:

我有以下型号:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end

如何创建查询以获取 5 本书,每本书都来自不同的作者?

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

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 postgresql-9.1


【解决方案1】:

让我们先得到 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    相关资源
    最近更新 更多