Without using any gems how do I do this in rails?
Main Category
Sub Category
Sub Category
Sub Category
Main Category
Sub Category
Sub Category
Sub Category
Main Category
Sub Category
Sub Category
Sub Category
I have a table that consists of | id | level1 | level2 |
Level 1 being the main category and Level 2 being the subcategory
I would like it displayed in the view like above.
After looking around on the internet everyone seems to recommend using acts-like-a-tree gem, but i want to avoid using them as I'm fairly new to rails and I would like to understand how to do things rather than turn to gems.
Your help is much apreciated
Model:
class Category < ActiveRecord::Base
belongs_to :catalogue
has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id", :dependent => :destroy
belongs_to :parent_category, :class_name => "Category"
end
Controller:
class CataloguesController < ApplicationController
layout 'main'
def index
@cats = Catalogue.all
end
def categories
@cat = Catalogue.find(params[:id])
end
end
View:
<ul class="unstyled-list">
<% @cat.categories.order([:level1]).each do |cat|%>
<li><%= cat.level1 %></li>
<li><%= cat.level2 %></li>
<% end %>
</ul>