您可以使用“通过”声明您的关系:
Subpage
belongs_to :page
has_one :topic, through: :page
Page
has_many :subpages
belongs_to :topic
Topic
has_many :pages
has_many :subpages, through: :pages
然后包含它并对其设置条件:
Subpage.includes(:topic).where(topics: { title: 'Hello World!' })
在你的情况下:
@subpages = Subpage.includes(:topic).where(topics: { id: @topic.id })
对于记录.includes()
,您必须在&方法中使用关系的名称.joins()
,我们在 where 子句中使用复数(以匹配表的名称):
如果用户属于_to :post
User.includes(:post).where(posts: { title: 'Post #1' })
#^ No plural #^ Always use the plural in the where clause
如果用户 has_many :posts
User.includes(:posts).where(posts: { title: 'Post #1' })
#^^ Plural because has_many :posts