ruby 嵌套集合宝石是如何工作的,我如何将它纳入我的项目?

k5ifujac  于 2024-01-07  发布在  Ruby
关注(0)|答案(1)|浏览(99)

最近有人建议我应该使用gem nested set来处理我当前的rails应用程序关系。(我之前的帖子/问题)我目前有3个模型,
类别有_many子类别
子类别属于类别,并且有许多产品。
Product belongs_to Subcategory.我想像这样显示它
+Category

  • 子类别
    产品展示
    产品展示
  • 子类别
    产品展示
    产品展示
    +Category
  • 子类别
    产品展示
    产品展示
    那么,如果我在nested_set中这样做,我将如何在我的模型中设置它?我是否会删除我的子类别和产品模型,而只是在Category模型中添加acts_as_nested_set?一旦我处理好模型,我将用什么来更新我的控制器操作,以便能够在我创建的嵌套集中创建节点?
    我想帮助我理解如何做CRUD,创建,读取,更新和销毁这个nested_set列表。
    下面是一些代码,我已经
    类别控制器:
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


任何帮助将非常感激。

7kjnsjlb

7kjnsjlb1#

我会选择一个类别和一个产品,就像这样:

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

字符串
这种方式是最灵活的,因为你可以把你的产品在任何一个类别,在任何一个层次。

相关问题