rails从子相关模型访问记录

时间:2013-11-05 19:41:31

标签: 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.where(topic => @topic)

该查询的外观如何?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用“通过”声明您的关系:

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子句中使用复数(以匹配表的名称):

如果用户belongs_to:post

User.includes(:post).where(posts: { title: 'Post #1' })
                 #^ No plural #^ Always use the plural in the where clause

如果用户has_many:发布帖子

User.includes(:posts).where(posts: { title: 'Post #1' })
                 #^^ Plural because has_many :posts
相关问题