每组返回第一条记录

时间:2015-07-07 17:05:02

标签: mysql ruby-on-rails ruby activerecord rails-activerecord

如何抓取一个ActiveRecord::Relation对象,其中包含每条记录为每个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

@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

应该返回:

author_id    book_id
   3           1
   1           2
   1           3
   2           4

2 个答案:

答案 0 :(得分:4)

# 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))

答案 1 :(得分:2)

您可以尝试inject

AuthorsBook.all
           .inject({}){|h, k| h[k.book_id] = k unless h.key? k.book_id; h}
           .values