How to create a model with categories that have subcategories (using Rails)?

I am creating a blog through Rails. I link message and category models through many-to-many relationships. How to include subcategories in this model?

+1
source share
2 answers

Hierarchy

The best way is to use one of the stones in the hierarchy, usually Ancestryor Closure_Tree, to create a tree structure for yours categories. You can then associate blogswith each category, creating the hierarchy functionality you need.

We achieved this earlier - using stone Ancestry:


Categories

enter image description here

, " ", , , .

, , , , categories, "", , , , hierarchy.

, sub_category.rb. - - Category - , .

:

#app/models/category.rb
class Category < ActiveRecord::Base
   has_ancestry #-> enables the "ancestry" gem
   has_and_belongs_to_many :posts
end

#app/models/post.rb
class Post < ActiveRecord::Base
   has_and_belongs_to_many :categories #-> you'll need a blogs_categories table with blog_id | category_id
end

, , " " , :

#app/controllers/posts_controller.rb
class PostsController < ApplicationController 
   def new
      @post = Post.new
   end

   def create
      @post = Post.new post_params
      @post.save
   end

    private

    def post_params
       params.require(:post).permit(:title, :body, :category_ids)
    end
end

, , /, Ancestry, "" :

enter image description here

, , ( ):

#app/views/categories/_category.html.erb
<ol class="categories">
    <% collection.arrange.each do |category, sub_item| %>
        <li>
            <!-- Category -->
            <%= link_to category.title, edit_admin_category_path(category) %>

            <!-- Children -->
            <% if category.has_children? %>
                <%= render partial: "category", locals: { collection: category.children } %>
            <% end %>

        </li>
    <% end %>
</ol>

:

#app/views/categories/index.html.erb
<%= render partial: "category", locals: { collection: @categories } %>
+2

, :

# post.rb
has_and_belongs_to_many :categories
has_many :sub_categories

# category.rb
has_and_belongs_to_many :posts
has_many :sub_categories


# sub_category.rb
belongs_to :category
belongs_to :post
# delegate attributes like so
delegate: :title, to: :category

0

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


All Articles