ActiveRecord在一个查询中查找关联记录的关联记录

时间:2016-02-24 01:13:03

标签: sql ruby-on-rails activerecord associations

我试图找到一个ActiveRecord和/或SQL方式,只对以下内容使用1个查询

获取作者撰写的所有章节,因为作者有很多书和一本书有很多章节

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
  has_many :chapters
end

class Chapter < ActiveRecord::Base
  belongs_to :book
end

这可行,但它使用两个查询

Chapter.where(book_id: author.books.map(&:id))

Book Load (0.4ms)  SELECT `books`.* FROM `books`  WHERE `books`.`author_id` = 1
Chapter Load (0.4ms)  SELECT `chapters`.* FROM `chapters`  WHERE `chapters`.`book_id` IN (1, 2, 3)

这样可行,但它返回的数组对象不是ActiveRecord关系对象

author.books.map(&:chapters)

1 个答案:

答案 0 :(得分:1)

通过关联使用has_many:

class Author < ActiveRecord::Base
  has_many :books
  has_many :chapters, through: :books
end

然后使用它:

author = Author.find(...)
author.chapters