嵌套Set Gem如何工作,如何将其合并到我的项目中?

时间:2012-02-17 05:13:38

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 nested-sets

我最近被告知,对于我目前的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 个答案:

答案 0 :(得分:2)

我会选择类别和类似产品:

class Product > ActiveRecord::Base
  belongs_to :category
end

class Category > ActiveRecord::Base
  has_many :products
  acts_as_nested_set
end

class CategoryController < ApplicationController
   def create

      @category = params[:id] ? Category.find(params[:id]).children.new(params[:category]) : Category.new(params[:category])

      if @category.save
          redirect_to products_path, :notice => "Category created! Woo Hoo!"
      else
          render "new" 
      end
   end

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

   def index
      @categories = params[:id] ? Category.find(params[:id]).children : Category.all
   end
end

#config/routes.rb your categories resource could be something like..
resources :categories do
   resources :children, :controller => :categories, 
                              :only => [:index, :new, :create]
end

这种方式最灵活,因为您可以将您的产品放在任何级别的任何类别中。