bcackerman
bcackerman

Reputation: 1554

Listing out parent then children

I have a database structure for Categories as id, name, parent_id.

A user can input a category and if it doesn't have a parent, the parent_id field will be set to 0.

My view is a basic loop shown here:

  <% @categories.each do |category| %>
    <tr class="<%= cycle('one', 'two') %>">
      <td>

        <%= indent(depth(category.id)) %> 
        <%= best_in_place category, :name %>

        <%= link_to(image_tag('/images/delete.png', :class => 'delete'), "categories/delete/#{category.id}")%>
      </td>
    </tr>
  <% end %>

The indent(depth(category.id)) function is just a way to get the depth of the child category and add that many -'s for visual purposes. http://d.pr/Ss8e

My problem is that the children aren't being listed under their respective parent. I'm not sure how to go about this, any advice? (group_by or another loop maybe?)

EDIT: Sorry for not being clear. The db structure I have is like this:

CATEGORIES
   id, name, parent_id, user_id
ITEMS
   id, name, category_id

I am looking to show the categories like this:

Parent1
  Child1
  Child2
Parent2
  Child1

Currently, the loop lists the items based on when they were created, it does not group them by parent_id like I'd like

Upvotes: 1

Views: 903

Answers (2)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

It seems that you should have:

category.rb

class Category < ActiveRecord::Base
  scope :parents, lambda {where("parent_ID IS NOT NULL")}
  scope: for_parent, lambda{|parent| where(:parent_id => parent.id)}

  def children
    Category.for_parent(self)
  end
end

Then in your controller:

@categories = Category.parents.all

And in your view

<% @categories.each do |category| %>
  <tr>
    <td><%= category.name %></td>
  </tr>
  <% category.children.each do |child| %>
    <tr>
      <td><%= child.name %></td>
    </tr>
  <% end %>
<% end %>

Upvotes: 1

Kyle Macey
Kyle Macey

Reputation: 8154

With a parent_id, category BELONGS_TO parent, and parent has_many :categories

<% @parents.each do |parent| %>
  <h1><%= parent.name %></h1>
  <% parent.categories.each do |category| %>
    <!-- Your stuff here -->
  <% end %>
<% end %>

Upvotes: 0

Related Questions