Return 每组第一条记录

Return first record per group

我如何抓取一个包含记录的 ActiveRecord::Relation 对象,其中每个记录都是 first author 每个 book.

# Models
class Author < ActiveRecord::Base
  has_many :authors_books
end

class AuthorsBook < ActiveRecord::Base
  belongs_to :author
  belongs_to :book
end

class Books < ActiveRecord::Base
  has_many :authors_books
end

@author_books = AuthorsBooks.all

示例 rows/records return 来自 @author_books.all

author_id    book_id
   3           1
   2           1
   3           1
   4           1
   1           2
   1           3
   2           4
   3           4

现在我只想抓取 第一个 author 每个 book:

应该return这样:

author_id    book_id
   3           1
   1           2
   1           3
   2           4

你可以试试 inject:

AuthorsBook.all
           .inject({}){|h, k| h[k.book_id] = k unless h.key? k.book_id; h}
           .values
# returns an array of active record objects
ary_authorbook_objs = AuthorsBook.all.group_by(&:book_id).collect{|k,v| v.first}

# transforms that array of active record objects into one ActiveRecord::Relation object
active_relation_object = AuthorsBook.where(id: ary_authorbook_objs.map(&:id))