在具有 rails 的深层嵌套关联中查找记录

Find records in deeply nested associations with rails

我有以下型号:

class Book < ApplicationRecord
  has_many :chapters
end

class Chapter < ApplicationRecord
  belongs_to :book
  has_many :pages
end

class Page < ApplicationRecord
  belongs_to :chapter
  has_many :paragraphs
end

class Paragrpah < ApplicationRecord
  belongs_to :page
end

现在我想获取特定书中所有段落的列表。类似于:

@parapgraphs = Paragraph.pages.chapters.book.where(:title => 'My Book')

当我这样做时,我得到:

undefined method 'chapters' for 'pages'

我正在使用 Rails 4.2 和 Ruby 2.2

如果您希望任何这些对象之间的链接始终存在并可查询,请考虑添加 has_many through 关系。

http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

如果是一次性查询,您可以这样做

@paragraphs = Paragraph.joins(page: { chapter: :book }).where(books: { title: 'My Book' })

试试这个

@paragraphs = Book.find_by(title: 'My book').chapters.map{ |c| c.pages.map{ |p| p.paragraphs.to_a }.flatten }.flatten