我有两个模型如下:
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
end
我的收藏品如下:
@books = Book.where(something: "...")
我想用独特的作者过滤这个系列。不从集合中选择唯一的作者。只收集具有author_id列唯一值的书籍。
UPD: 例如,我有集合
> #<ActiveRecord::Relation
[#<Book id: 1, title: "Tails", author_id: 1>,
<Book id: 2, title: "Tails part 2", author_id: 1>,
<Book id: 3, title: "Tails part 3", author_id: 1>,
<Book id: 4, title: "Stories part 1", author_id: 5>,
<Book id: 5, title: "Stories part 2", author_id: 5>]>
应该是这样的:
> #<ActiveRecord::Relation [
<Book id: 1, title: "Tails", author_id: 1>,
<Book id: 4, title: "Stories part 1", author_id: 5>
]>
答案 0 :(得分:1)
实现此目的的最直接方法是首先找到您要过滤的作者ID。
author_ids = Author.where(first_name: 'Deborah').pluck(:id)
我们说author_ids
现在包含数组[1, 2, 3]
。现在,您可以使用此作者ID数组来查找这些作者的书籍。
Book.where(author_id: author_ids)
这可以理解为“查找author_id在此ID列表中的书籍”。生成的SQL将是:
SELECT "books".* FROM "books" WHERE "books"."author_id" IN (1, 2, 3)
修改强>
在问题作者澄清后,我相信这就是所需要的:
Book.select('DISTINCT ON (author_id) *')