Management categories with show parent category and sub category in rails

RUBY ON RAIL

Posted on 2016-11-30 22:20:17


You should add line to routes.rb file

resources :categories

1. Create table categories with migrate

class CreateCategories < ActiveRecord::Migration[5.0]

  def change

    create_table :categories do |t|

      t.integer :parent_category_id

      t.string :name, :null => false

 

      t.timestamps

    end

  end

end

2. Mode categoy.rb

class Category < ApplicationRecord

  validates :name,  presence: true

  has_many :subcategories, :class_name => "Category", :foreign_key => :parent_category_id, :dependent => :destroy

  has_one :parent, :class_name => "Category", :primary_key => :parent_category_id, :foreign_key => :id

 

end

 

The content in model :

- validate for field name when create and edit category

- Table categoy join with itself  by parent_category_id. A parent category has many subcategories.

- :dependent => :destroy, this is deleted all subcategories when you delete a parent category.

- One parent category join with sub category by id.

3. In controller file

def index

    @categories = Category.includes(:subcategories)

  end

- get all parent categories in table and each parent category is included sub-categories related.

4. In view file

I used haml file replace main view file ruby on rails .html.erb

index.haml

= provide(:title, 'All categories')

%h1

  List of categories

= render 'shared/messages'

.button

  = link_to "New Category", new_category_path

= render 'table_categories'

render  _table_categories.haml

%table.table.table-hover

  %thead

    %tr

      %th

        Name

      %th

        Action

  %tbody

    - @categories.each do |category|

      -if category.parent_category_id.blank?

        %tr

          %td

            = link_to category.name, [:edit, category]

          %td

            = link_to "Delete", category, method: :delete, data: { confirm: "Are You sure?" }

        = render partial: 'subcategory', locals: {subcategories: category.subcategories} if category.subcategories.present?

render _subcategory.haml

- subcategories.each do |sub|

  %tr.child_color_bg

    %td.child_category_name

      = link_to sub.name, [:edit, sub]

    %td

      = link_to "Delete", sub, method: :delete, data: { confirm: "Are You sure?" }

 

5. CSS file

/* category index */

 

.child_category_name{

  padding-left: 40px !important;

}

.child_color_bg{

  background-color: #ddd;

}

 

 

This view is used bootstrap. You should use bootstrap to show same layout with image result