我最近被告知,对于我目前的rails应用程序关系,我应该使用gem nested set . (我以前的主题/问题here)我目前有3个型号,
类别has_many子类别
子类别belongs_to类别和has_many产品 .
产品belongs_to子类别 . 我想要显示这样的东西
类别
----子目录
-
-
-
- 产品
-
-
-
-
-
- 产品
----子目录
- 产品
-
-
-
-
-
- 产品
-
-
-
-
-
- 产品
-
-
类别
----子目录
-
-
-
- 产品
-
-
-
-
-
- 产品
-
-
所以如果我在nested_set中这样做,我将如何在我的模型中设置它?我会删除子类别和产品模型,只需在Category模型中添加acts_as_nested_set吗?一旦我对模型进行了处理,我将如何更新我的控制器操作,以便能够在我创建的嵌套集中创建节点?
我想只是帮助我理解如何进行CRUD,创建,读取,更新和销毁这个嵌套列表 .
这是我已经有的一些代码
分类控制器:
class CategoriesController < ApplicationController
def new
@category = Category.new
@count = Category.count
end
def create
@category = Category.new(params[:category])
if @category.save
redirect_to products_path, :notice => "Category created! Woo Hoo!"
else
render "new"
end
end
def edit
@category = Category.find(params[:id])
end
def destroy
@category = Category.find(params[:id])
@category.destroy
flash[:notice] = "Category has been obliterated!"
redirect_to products_path
end
def update
@category = Category.find(params[:id])
if @category.update_attributes(params[:category])
flash[:notice] = "Changed it for ya!"
redirect_to products_path
else
flash[:alert] = "Category has not been updated."
render :action => "edit"
end
end
def show
@category = Category.find(params[:id])
end
def index
@categories = Category.all
end
end
分类型号:
class Category < ActiveRecord::Base
acts_as_nested_set
has_many :subcategories
validates_uniqueness_of :position
scope :position, order("position asc")
end
子类别模型:
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
scope :position, order("position asc")
end
最后,产品型号:
class Product < ActiveRecord::Base
belongs_to :subcategory
has_many :products
scope :position, order("position asc")
end
任何帮助将非常感激 .
1 回答
我会选择类别和产品,如下所示:
这种方式最灵活,因为您可以将您的产品放在任何级别的任何类别中 .