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>
Create a model that has references to itself for a sub-category (or a sub-sub-category, etc):
has_many
defines asubcategories
association of the model typeCategory
. Ie it uses the same table.belongs_to
defines a relation back to the parent category (optional, not required)For more information on model associations,
has_many
orbelongs_to
, read the Associations Basics Guide.To create the table use this migration:
Note: this table format is (slightly) different than you proposed, but I suppose that this is not a real problem.
The Migrations Guide contains more information on database migrations.
In your controller use
to find all categories without a parent, ie the main categories
To find all sub-categories of any given category use:
To add a new category use:
It creates a new category and sets the parent, if it is provided (otherwise it becomes a Main Category)
Note: I used the old rails syntax (due to laziness), but for Rails 3.2 the principle is the same.
In your
categories/index.html.erb
you can use something like this:It shows the name of the selected category (or Main Category) and all of its sub-categories (in a nice table). It links to all sub-categories, showing a similar layout, but for the sub-category. In the end it adds a 'new sub-category' link and a 'back' link.
Note: My answer became a bit extensive... I copied and modified it from one of my projects that uses a similar construction (for (sub-)menus). So hopefully I did not break anything during the modifications... :)