Subcategory Rails

How to find and manage subcategories? (the find_subcategory method that I defined does not work.)

class CategoriesController < ApplicationController
before_action :find_category, only: [:show]

def index
    @categories = Category.order(:name)
end

def show
end


private

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

def find_subcategory
    @subcategory = Category.children.find(params[:parent_id])
end

end

I use act_as_tree gem which has:

 root      = Category.create("name" => "root")
  child1    = root.children.create("name" => "child1")
  subchild1 = child1.children.create("name" => "subchild1")



root.parent   # => nil
  child1.parent # => root
  root.children # => [child1]
  root.children.first.children.first # => subchild1
+4
source share
2 answers

It is not clear what you want your find_subcategory method to execute, but if you want it to find all the subcategories of the category with id in params [: id], then change it to

def find_subcategories
  @subcategories = Category.where(:parent_id => params[:parent_id]).all
end

In your original, you are simply looking for one subcategory, and if you need only one category, you can simply download it from it.

+2
source

I know that you accepted the answer, but I did it before , and therefore it would be useful to explain how we did it:


-, . acts_as_tree - acts_as_tree , ancestry, , - ancestry (parent, child ..).

ancestry - , acts_as_tree:

#app/models/category.rb
class Category < ActiveRecord::Base
   has_ancestry #-> enables the ancestry gem (in your case it should be "acts_as_tree"
end

ancestry ( parent_id) categories ( ) child, :

@category.parent
@category.children

... ..

-

, child ( ).

. ancestry/acts_as_tree - .

parent "" :

enter image description here

ancetry. , acts_as_tree, ( ), :

#app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
   def index
      @categories = Category.all
   end
end

#app/views/categories/index.html.erb
<%= render @categories %>

#app/views/categories/_category.html.erb
<%= category.name %>
<%= render category.children if category.has_children? %>

:

enter image description here


:

@subcategories = Category.where parent_id: @category.id

, :

#config/routes.rb
resources :categories

#app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
   def show
      @category = Category.find params[:id]
   end
end

:

#app/views/categories/show.html.erb
<% @category.children.each do |subcategory| %>
   <%= subcategory.name %>
<% end %>

enter image description here

+2

Source: https://habr.com/ru/post/1612203/


All Articles