问题
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
回答1:
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' })
回答2:
Try this instead
@paragraphs = Book.find_by(title: 'My book').chapters.map{ |c| c.pages.map{ |p| p.paragraphs.to_a }.flatten }.flatten
来源:https://stackoverflow.com/questions/36343965/find-records-in-deeply-nested-associations-with-rails