fnllc
fnllc

Reputation: 3127

Find records in deeply nested associations with rails

I have the following models:

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

Now I want to get a list of all paragraphs in a specific book. Something like:

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

When I do this, I get:

undefined method 'chapters' for 'pages'

I'm using Rails 4.2 and Ruby 2.2

Upvotes: 2

Views: 1844

Answers (2)

Alexa Y
Alexa Y

Reputation: 1854

If you want links between any of those objects to always be present and queryable, consider adding a has_many through relationship.

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

If it's more of a one time query, you could do something like this

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

Upvotes: 6

Jacob Rastad
Jacob Rastad

Reputation: 1171

Try this instead

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

Upvotes: 1

Related Questions