【发布时间】:2016-02-26 23:28:02
【问题描述】:
在这个应用程序中,我有一个父子树。模型(带有一些数据)如下所示:
Subjects
Subject_id Subject_name Parent_id
1 Plants 0
2 Animals 0
3 Bacteria 0
4 Tree 1
5 Grass 1
6 Dog 2
7 Pine 4
关系如下:
class Subject < ActiveRecord::Base
belongs_to :parent, class_name: "Subject"
has_many :children, class_name: "Subject", foreign_key: "parent_id"
end
我想获取 parent_id 为 0 的父母。我该怎么做?
我知道一种解决方案是创建一个根父级,并使用 .children 调用它以获取根父级的子级,但这不是我想要做的。
【问题讨论】:
-
我在控制台试了一下,得到 NameError: uninitialized constant Parent
-
对不起
Subject.where( :parent_id => 0 )。我已经监督了 class_name。 -
这会让我得到 Subject_id = 0 的主题。我正在尝试让 Parent_id = 0 的主题
-
就是这样,谢谢。我将阅读更多关于那里的 .where 部分。如果您想将您的评论作为答案,我会选择它作为正确答案。
标签: ruby-on-rails