【问题标题】:Rails Adjacency List - Parent Child Tree - Get rootRails 邻接列表 - 父子树 - 获取根目录
【发布时间】: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 =&gt; 0 )。我已经监督了 class_name。
  • 这会让我得到 Subject_id = 0 的主题。我正在尝试让 Parent_id = 0 的主题
  • 就是这样,谢谢。我将阅读更多关于那里的 .where 部分。如果您想将您的评论作为答案,我会选择它作为正确答案。

标签: ruby-on-rails


【解决方案1】:

以前的评论

Subject.where( :parent_id => 0 )

【讨论】:

    【解决方案2】:

    首先获取 Active 记录时,以大写字母开头。 其次,使其单数化。

    subjects.find_by
    

    应该是

    Subject.find_by
    

    三、数据库中命名表字段的用户小写,like.

    Parent_id >> parent_id
    

    接下来,你的has_many关系应该是Parent Model

    让我们这样说:

    父模型:

    has_many :subjects
    

    主题模型:

    belongs_to :parent
    

    从主题控制器获取父级。

    @subject = Subject.all
    

    在视图中,你必须像这样迭代它:

    <% @subject.each do |sub| %>
      <%= sub.parent.title %> //title field for ex.
    <% end %>
    

    但是如果你想得到一个 Subject 并且它是父数据,你可以这样做:

    @subject = Subject.first
    @subject.parent.title //example field from Parent Table
    

    【讨论】:

    • 嗨,Aldrien,当你说“接下来,你 has_many 关系应该在父模型中”时,我有点困惑。我的模型是自引用的。这就是它构建树结构的方式。
    猜你喜欢
    • 1970-01-01
    • 2017-01-18
    • 2021-08-17
    • 2021-11-29
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    相关资源
    最近更新 更多