Oleg Oleg - 1 month ago 12
Ruby Question

Iterate records in rails view and controller

How can i output categories and subcategories in rails view? Like this:


  • First category name


    • First category child 1 name

    • First category child 2 name

    • First category child 3 name


  • Second category name


    • Second category child 1 name

    • Second category child 2 name

    • Second category child 3 name




my schema.rb:

create_table "categories", force: :cascade do |t|
t.integer "title"
t.boolean "state", default: true
t.integer "parent_id" # id of parent category
end


my categories_controller.rb

def show
@category = Category.find(params[:id])
#child categories of current parent category
@child_categories = Category.where(parent_id: @category.id)
#subchild categories of current parent category
@child_categories.each do |category|
@subchild_categories = Category.where(parent_id: category.id)
end
end


my show.html.erb

<% if @child_categories.any? %>
<ul>
<% @child_categories.each do |child| %>
<li>
<%= child.title %>
<ul>
<% @subchild_categories.each do |subchild| %>
<li><%= subchild.title %></li>
<% end %>
</ul>
</li>
<% end %>
</ul>
<% end %>


Now i get something like this:


  • First category name


    • Second category child 1 name

    • Second category child 2 name

    • Second category child 3 name


  • Second category name


    • Second category child 1 name

    • Second category child 2 name

    • Second category child 3 name



Answer
#try this:    

def show
    @category = Category.find(params[:id])

    @child_categories = Category.where(parent_id: @category.id)

   @subchild_categories = {}
   @child_categories.each do |category|
     @subchild_categories[category.title] = Category.where(parent_id: category.id)
   end
end



#and in view:

<% @child_categories.each do |child| %>
   <li>
      <%= child.title %>
      <ul>
          <% @subchild_categories[child.title].each do |subchild| %>
              <li><%= subchild.title %></li>
        <% end %>
    </ul>
  </li>
<% end %>