Ruby on rails 来自子相关模型的rails访问记录
我不知道答案的简单任务: 我有3个模型:主题、页面和子页面Ruby on rails 来自子相关模型的rails访问记录,ruby-on-rails,Ruby On Rails,我不知道答案的简单任务: 我有3个模型:主题、页面和子页面 topics has_many pages pages has_many subpages pages belongs_to topics subpages belongs_to pages 我根据URL slug查找主题: @topic = Topic.find_by_slug(params[:topic]) 现在我想访问所有与主题相关的子页面,所以实际上我想“跳过”页面 @subpages = Subpage.w
topics has_many pages
pages has_many subpages
pages belongs_to topics
subpages belongs_to pages
我根据URL slug查找主题:
@topic = Topic.find_by_slug(params[:topic])
现在我想访问所有与主题相关的子页面,所以实际上我想“跳过”页面
@subpages = Subpage.where(topic => @topic)
这个查询看起来怎么样
谢谢您的帮助。您可以通过以下方式声明您与a的关系:
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子句中使用复数形式(以匹配表的名称):
如果用户属于:post
User.includes(:post).where(posts: { title: 'Post #1' })
#^ No plural #^ Always use the plural in the where clause
如果用户有很多:帖子
User.includes(:posts).where(posts: { title: 'Post #1' })
#^^ Plural because has_many :posts
但是子页面属于页面,并且没有很多页面。这是一个1:n的关联,而不是n:n。