使用rails查找与嵌套关联的记录

use*_*194 2 ruby activerecord ruby-on-rails where-clause ruby-on-rails-4

我有以下型号:

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
Run Code Online (Sandbox Code Playgroud)

现在我想得到一本特定书中所有段落的清单.就像是:

@parapgraphs = Paragraph.pages.chapters.book.where(:title => 'My Book')
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到:

undefined method 'chapters' for 'pages'
Run Code Online (Sandbox Code Playgroud)

我正在使用Rails 4.2和Ruby 2.2

Ale*_*a Y 5

如果您希望任何这些对象之间的链接始终存在且可查询,请考虑添加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' })
Run Code Online (Sandbox Code Playgroud)