title: Rails: categories and sub-categories model rails
body: <p>Without using any gems how do I do this in rails?</p>
  
  <p>Main Category<br>
   Sub Category<br>
   Sub Category<br>
   Sub Category    </p>
  
  <p>Main Category<br>
   Sub Category<br>
   Sub Category<br>
   Sub Category    </p>
  
  <p>Main Category<br>
   Sub Category<br>
   Sub Category<br>
   Sub Category    </p>
  
  <p>I have a table that consists of | id | level1 | level2 |</p>
  
  <p>Level 1 being the main category and Level 2 being the subcategory</p>
  
  <p>I would like it displayed in the view like above.</p>
  
  <p>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.</p>
  
  <p>Your help is much apreciated</p>
  
  <p>Model:</p>
  
  <pre><code>class Category &lt; ActiveRecord::Base
  belongs_to :catalogue
      has_many :subcategories, :class_name =&gt; "Category", :foreign_key =&gt; "parent_id", :dependent =&gt; :destroy
  belongs_to :parent_category, :class_name =&gt; "Category"
  end
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>class CataloguesController &lt; ApplicationController
    layout 'main'
    def index
     @cats = Catalogue.all
    end
  
    def categories
     @cat = Catalogue.find(params[:id])
    end
  
  end
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>&lt;ul class="unstyled-list"&gt;
  
      &lt;% @cat.categories.order([:level1]).each do |cat|%&gt;
          &lt;li&gt;&lt;%=  cat.level1 %&gt;&lt;/li&gt;
          &lt;li&gt;&lt;%= cat.level2 %&gt;&lt;/li&gt;
      &lt;% end %&gt;
  &lt;/ul&gt;
  </code></pre>