Question

Im trying to make a category system with parents. Here is how my database is structured.
- id
- name
- parent_id

Basically what I want it to do is check if there is a parent id, and if so then check if the parent id, and if that parent has a parent id, and so on. Then output the parents in order until it reached the child.

Currently what I am doing (in Ruby/Ruby on Rails) is this:

<% @cat = Category.find_by_id(@project.category) %>
<% if @cat.parent_id.nil? %>
    <%= @cat %>
<% else %>
  <%= Category.find_by_id(@cat.parent_id).name%> => <%= @cat.name %>
<% end %>

The problem with this is that it only gets one parent. I need it to recurse and constantly gather the parent until it hits and end, and also I dont want it to take up too much memory. Any help would be appreciated. Thanks! :)

Was it helpful?

Solution

Add a method on your model to search for the parent

class Category
  # inline, less memory usage 
  def last_parent
    last = self
    while last.parent
      last = last.parent  
    end
    last
  end

  # recursive, better readability
  def last_parent_recursive
    if parent
      parent.last_parent_recursive
    else
      self
    end
  end
end

then, on your view:

<%= @cat.last_parent %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top