O
O
Oleg Kulakov2016-04-26 19:55:44
Ruby on Rails
Oleg Kulakov, 2016-04-26 19:55:44

Ruby on rails: How to display a hierarchical list?

You need to create a nested category hierarchy in your project.
Migration:

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :title
      t.references :parent, index: true
      t.timestamps null: false
    end
  end
end

According to the model:
class Category < ActiveRecord::Base
  has_many :subordinates, class_name: "Category",
           foreign_key: "parent_id"

  belongs_to :parent, class_name: "Category"


end

(material taken from here )
Actually the question is: How to check if a category has subordinates and, if so, display them?
PS at least kick in the place where you can read about it for the noob

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Kulakov, 2016-04-26
@Morphine43

The following code worked correctly:

<% if category.subordinates.count >=1 %>
          <%= category.subordinates.first.title %>
              <% end %>

accordingly, subordinates contains many objects (based on the has_many relation), which means that the category.subordinates.title expression is incorrect (we request 1 title from many objects). Conclusion: parsing subordinates through each

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question