2

に深くネストされた団体のレコードを検索:私は次のモデルを持っているレール

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') 

、私が手:私はRailsの4.2とRuby 2.2

+0

章の方法は、のように「の章」でなければなりません:Parapoints.includes(page:{chapter::book})。ここで(books:{title():@ title:=> 'My Book') – bkunzi01

+0

@parapgraphs = Paragraphs.pages.chapter.book.where : '私の本' }) '(http://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children/に似ています) – MrYoshiji

答えて

5

を使用してい

undefined method 'chapters' for 'pages' 

をあなたが常にあることを、これらのオブジェクトのいずれかの間のリンクをしたい場合has_many through関係を追加することを検討してください。それは1時間クエリのよりなら

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

することは、あなたがこの

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

where句は、リレーションの名前ではなくテーブルの名前を使用します(どこに(書籍:{タイトル: 'いくつかのタイトル'})) ') – MrYoshiji

+0

あなたは正しい、私の間違いだ! –

1

のようなものは、これを試してみてください可能性が代わりに

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

これには計算に時間がかかることがあります。できるだけSQLを使用し、Rubyを使用しないでください。特にこのケースでは – MrYoshiji

+0

が真実で、これはもっと速かった –

関連する問題