在不使用任何gem的情况下,我如何在rails中做到这一点?
主要类别
子类别
子类别
子类别
主要类别
子类别
子类别
子类别
主要类别
子类别
子类别
子类别
我有一张表,其中包括|身份证|第一级|第二级|
1级为主类别,2级为子类别
我想它显示在上面的视图一样。
在互联网上四处寻找之后,每个人似乎都推荐使用acts like-a-tree gem,但我想避免使用它们,因为我对rails相当陌生,我想了解如何做事情,而不是转向gem。
非常感谢你的帮助
型号:
class Category < ActiveRecord::Base
belongs_to :catalogue
has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id", :dependent => :destroy
belongs_to :parent_category, :class_name => "Category"
end
控制器:
class CataloguesController < ApplicationController
layout 'main'
def index
@cats = Catalogue.all
end
def categories
@cat = Catalogue.find(params[:id])
end
end
查看:
<ul class="unstyled-list">
<% @cat.categories.order([:level1]).each do |cat|%>
<li><%= cat.level1 %></li>
<li><%= cat.level2 %></li>
<% end %>
</ul>
3条答案
按热度按时间yxyvkwin1#
创建一个子类别(或子子类别等)引用自身的模型:
has_many
定义模型类型Category
的subcategories
关联,即它使用相同的表。belongs_to
定义了返回父类别的关系,可通过@category.parent_category
访问有关模型关联
has_many
或belongs_to
的更多信息,请阅读Associations Basics Guide。要使用此迁移创建表:
Migrations Guide包含有关数据库迁移的详细信息。
在控制器中使用
查找没有父类别的所有类别(主类别
要查找任何给定类别的所有子类别,请用途:
要添加新类别,请用途:
它创建一个新类别并设置父类别(如果提供了父类别)(否则它将成为主类别)
注意:我使用了旧的Rails语法(由于懒惰),但是对于现代版本的Rails,原理是相同的。
在你的
categories/index.html.erb
中,你可以使用如下代码:它显示所选类别(或主类别)的名称及其所有子类别(在一个漂亮的表格中)。它链接到所有子类别,显示类似的布局,但子类别。最后,它添加了一个“新子类别”链接和一个“返回”链接。
j2qf4p5b2#
bt1cpqcv3#
这就是你如何处理分类和课程或帖子
这是获取所有类别和课程的方法
这是查询的响应