ruby-on-rails – 类别和子类别模型栏

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 类别和子类别模型栏前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
没有使用任何宝石,我该如何在轨道上这样做?

主要类别
子类别
子类别
子类别

主要类别
子类别
子类别
子类别

主要类别
子类别
子类别
子类别

我有一个由…组成的表id | level1 | level2 |

1级是主要类别,2级是子类别

我想在上面的视图中显示.

在互联网上环顾四周后,每个人都似乎推荐使用类似行为的树木宝石,但是我想避免使用它们,因为我是一个很新的轨道,我想了解如何做事情,而不是转向宝石.

你的帮助很重要

模型:

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>

解决方法

创建一个对子类别(或子子类别等)具有引用的模型:
class Category < ActiveRecord::Base
  has_many :subcategories,:dependent => :destroy
  belongs_to :parent_category,:class_name => "Category"
end

> has_many定义模型类型类别的子类别关联.即它使用相同的表.
> belongs_to将一个关系定义回父类(可选,不需要)

有关模型关联的更多信息,请参阅has_many或belongs_to,阅读Associations Basics Guide.

要创建表,请使用此迁移:

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :category do |t|
      t.string      :text
      t.references  :parent
      t.timestamps
    end
  end
end

注意:这个表格格式与您提出的(略)不同,但我认为这不是一个真正的问题.

Migrations Guide包含有关数据库迁移的更多信息.

在你的控制器使用

def index
  @category = nil
  @categories = Category.find(:all,:conditions => {:parent_id => nil } )
end

找到没有父母的所有类别,即主要类别

查找任何给定类别的所有子类别使用:

# Show subcategory
def show
  # Find the category belonging to the given id
  @category = Category.find(params[:id])
  # Grab all sub-categories
  @categories = @category.subcategories
  # We want to reuse the index renderer:
  render :action => :index
end

添加新类别使用:

def new
  @category = Category.new
  @category.parent = Category.find(params[:id]) unless params[:id].nil?
end

它创建一个新类别并设置父级(如果提供)(否则它成为主类别)

注意:我使用旧的rails语法(由于懒惰),但对于Rails 3.2,原理是一样的.

在你的类别/ index.html.erb中,你可以使用这样的东西:

<h1><%= @category.nil? ? 'Main categories' : category.text %></h1>
<table>
<% @categories.each do |category| %>
<tr>
  <td><%= link_to category.text,category_path(category) %></td>
  <td><%= link_to 'Edit',edit_category_path(category) unless category.parent.nil? %></td>
  <td><%= link_to 'Destroy',category_path(category),:confirm => 'Are you sure?',:method => :delete unless category.parent.nil? %></td>
</tr>
<% end %>
</table>
<p>
  <%= link_to 'Back',@category.parent.nil? ? categories_path : category_path(@category.parent) unless @category.nil? %>
  <%= link_to 'New (sub-category',new_category_path(@category) unless @category.nil? %>
</p>

显示所选类别(或主类别)的名称及其所有子类别(在一个不错的表格中).它链接到所有子类别,显示类似的布局,但是对于子类别.最后,它添加了一个“新的子类别”链接和“后退”链接.

注意:我的答案变得有点广泛…我从我使用类似结构的一个项目((子菜单))中复制并修改了它.所以希望我在修改过程中没有打破任何东西…

猜你在找的Ruby相关文章