【发布时间】:2015-07-07 17:05:01
【问题描述】:
如何获取包含记录的 ActiveRecord::Relation 对象,其中每个记录是每个 book 的第一个 author。
# 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
现在我只想获取 first author per book:
应该返回这个:
author_id book_id
3 1
1 2
1 3
2 4
【问题讨论】:
-
@author_books 是根据 AuthorBooks 表的 id 排序的结果。你想要每本书的第一作者然后创建吗?我的意思是基于 AuthorBooks 记录的 created_at 时间。
-
定义第一作者?
-
可能这就是你想要的...
AuthorsBooks.all.group_by(&:book_id).collect{|k,v| v.first} -
这对你有用吗?
-
很高兴我能帮上忙...
标签: mysql ruby-on-rails ruby activerecord rails-activerecord