Find records in deeply nested associations with rails

▼魔方 西西 提交于 2021-02-05 07:14:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!