Hopstream
Hopstream

Reputation: 6451

ActiveAdmin -- How to display category taxonomy? (in tree type hierarchy)

I have a model category which contains a field called category.parent_id which is used to create a taxonomy (top level categories with sub categories).

At the moment my index page shows the categories as:

Top level category
Sub category
Sub category
Top category

How could I order them in a proper taxonomy (i.e. first all top level categories are taken from db then sub categories, etc) and shown as the following:

Top level category
-- Sub category
-- Sub category
Top category

Upvotes: 2

Views: 3053

Answers (2)

davidb
davidb

Reputation: 8954

You could create a self referencing Model like this in you case (In app/model/category.rb):

belongs_to :parent, :class_name => 'Category', :foreign_key => 'parent_id'
has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'

Then you can create a scope for the parents

scope :parents, where("parent_id IS NULL")

And in view you can use iteration like this

<ul>
<% Category.all.parents.each do |parent| %>
     <li class="parent"><%= link_to parent.name, parent %></li>
     <% parent.children.each do |child| %>
          <li class="sub"><%= link_to child.name, child %></li>
     <% end %>
<% end %>
</ul>

Hope this helps you!

//I read what I wanted to read,... I didn't see it's about active admin. Thought it's about ActiveRecord -.-

Upvotes: 1

Hopstream
Hopstream

Reputation: 6451

After hours of banging my head against the wall, I came up with this solution:

ActiveAdmin can not render a partial for the entire index, however you can render one for a single column!

So the work around was to create a column for sub categories like this:

    column "Sub Categories" do |category|
      children = Category.children(category.id)
      if children.present?
        render :partial => "children", :locals => { :children => children }
      end
    end

And then in _children.html.erb view partial you can print out the list like this:

    <% children.each do |child| %>
        <p><%= link_to child.name, edit_admin_category_path(child) %></p>
    <% end %>

Upvotes: 3

Related Questions