user3456978
user3456978

Reputation: 248

Rails Adjacency List - Parent Child Tree - Get root

In this app I have a parent-child tree. The model (with some data) looks like this:

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

The relationship looks like this:

class Subject < ActiveRecord::Base
  belongs_to :parent, class_name: "Subject"
  has_many :children, class_name: "Subject", foreign_key: "parent_id"
end

I want to get the parents with parent_id 0. How do I do that?

I know one solution is to create a root parent, and call that with .children to get the root parents children, but that's not what I want to do.

Upvotes: 0

Views: 684

Answers (2)

devanand
devanand

Reputation: 5290

former comment

Subject.where( :parent_id => 0 )

Upvotes: 1

aldrien.h
aldrien.h

Reputation: 3635

First when getting Active record, starts with capital letter. Secondly, make it singular.

subjects.find_by

should be

Subject.find_by

Third, user lowercase in naming table field in Database, like.

Parent_id >> parent_id

Next, you has_many relationship should be in Parent Model

Let say like this:

Parent model:

has_many :subjects

Subject Model:

belongs_to :parent

Get parent from Subject Controller.

@subject = Subject.all

In view, you have to iterate it like:

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

But if you want to get one Subject and it's parent data, you can do like:

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

Upvotes: 0

Related Questions