在与Rails深度嵌套的关联中查找记录 [英] Find records in deeply nested associations with rails
本文介绍了在与Rails深度嵌套的关联中查找记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下型号:
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')
这样做,我得到:
undefined method 'chapters' for 'pages'
我正在使用Rails 4.2和Ruby 2.2
I'm using Rails 4.2 and Ruby 2.2
推荐答案
如果您希望这些对象之间的链接始终存在并且可查询,请考虑通过关系添加has_many.
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' })
这篇关于在与Rails深度嵌套的关联中查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文