2014-09-19 49 views

回答

2

Hierarchy

最好的办法是使用层次的一个宝石,通常AncestryClosure_Tree为您的categories创建一个“树”型结构。然后,您可以将blogs与每个类别关联起来,创建您所需的层次结构功能。

之前我们已经取得了这一点 - 使用Ancestry宝石:


分类

enter image description here

你可以从上面的图片中, “秘密武器” 你看缺少的是您的类别不在基于层次结构的结构中。

这个很重要的原因是因为如果您将博客文章与特定的categories相关联,为了使这些类别实现您所期望的“子类别”结构,您需要能够创建一个支持它的系统,因此hierarchy宝石。

具体而言,您目前正致力于创建单独的sub_category.rb模型。正确的做法是保持一个模型 - Category - 并使用层次结构gem为您提供树基础结构。

下面是我们如何做到这一点:

#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

要做到这一点,你只需要使用的部分,这将call the children of the parent objects,让你展现出“树”类型的层次结构(以及创建子类别):

#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 } %> 
0

创建 - 行业标准模型,就像这样:

# 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 

了解更多关于他们在rails guide