如何抓取一个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
答案 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