2015-10-19 66 views
4

如何查找和管理子类别? (我所定义的find_subcategory方法似乎并没有工作。)导轨子类别

class CategoriesController < ApplicationController 
before_action :find_category, only: [:show] 

def index 
    @categories = Category.order(:name) 
end 

def show 
end 


private 

def find_category 
    @category = Category.find(params[:id]) 
end 

def find_subcategory 
    @subcategory = Category.children.find(params[:parent_id]) 
end 

end 

我使用acts_as_tree宝石,其中有:

root  = Category.create("name" => "root") 
    child1 = root.children.create("name" => "child1") 
    subchild1 = child1.children.create("name" => "subchild1") 



root.parent # => nil 
    child1.parent # => root 
    root.children # => [child1] 
    root.children.first.children.first # => subchild1 

回答

2

目前尚不清楚你希望你的find_subcategory方法是什么这样做,但如果你希望它找到ID为类别的所有子类别params中[:编号],然后将其更改为

def find_subcategories 
    @subcategories = Category.where(:parent_id => params[:parent_id]).all 
end 

在你原来你只是在寻找一个子类别,如果你只是洼nt一个类别,你可能只是从它的ID加载它。

+0

太好了!这正是我的意图。 – Liroy

+0

只是一个小点。 '.all'在这里是多余的。 :-) – Drenmi

+1

@Drenmi有趣的是,我没有把'.all'放在我原来的答案中,然后我回去添加它,因为我认为它更明显我们想要一个集合而不是单个记录。 –

2

我知道你接受了答案,但I've done this before,所以它可能是有益的解释我们是如何做到的:


首先,我们使用了祖先的宝石。 我觉得acts_as_tree已被弃用 - acts_as_treeancestry好,我忘了为什么我们现在用它 - 在非常类似的方式(parent列,child方法等)ancestry作品。

我将解释我们的实现与ancestry - 希望它会给你acts_as_tree一些想法:

#app/models/category.rb 
class Category < ActiveRecord::Base 
    has_ancestry #-> enables the ancestry gem (in your case it should be "acts_as_tree" 
end 

这将允许你在你的categories模型填充ancestry(你的情况parent_id)列,和(最重要的),让你连接到对象模型的能力call the child methods

@category.parent 
@category.children 

...等

-

这里要注意的重要一点是我们如何是能够调用child对象(这将是小类你的情况)。

你的方法是创建单独的对象,并让它们相互继承。 ancestry/acts_as_tree的美丽是他们增加的方法。

任何物体与正确parent IDS可以称之为自己的“孩子”作为关联数据:

enter image description here

在我们的例子中,我们能够使用ancetry列中的所有对象相关联。这比acts_as_tree稍微棘手,因为你必须提供在列(这是跛)的整个层次,但是结果还是一样:

#app/controllers/categories_controller.rb 
class CategoriesController < ApplicationController 
    def index 
     @categories = Category.all 
    end 
end 

#app/views/categories/index.html.erb 
<%= render @categories %> 

#app/views/categories/_category.html.erb 
<%= category.name %> 
<%= render category.children if category.has_children? %> 

这将输出的子类别您:

enter image description here


如何查找和管理子类别

你可以这样说:

@subcategories = Category.where parent_id: @category.id 

如果你有你的祖先设置正确,你应该能够使用以下命令:

#config/routes.rb 
resources :categories 

#app/controllers/categories_controller.rb 
class CategoriesController < ApplicationController 
    def show 
     @category = Category.find params[:id] 
    end 
end 

这将允许你用途:

#app/views/categories/show.html.erb 
<% @category.children.each do |subcategory| %> 
    <%= subcategory.name %> 
<% end %> 

enter image description here

+0

这非常有用。你还可以发布你的类别模型/结构? – Liroy

+0

https://github.com/richpeck/accountancy_demo/blob/master/app/models/category.rb如果您愿意,我可以发布相关代码 –