2015-10-19 71 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如果您願意,我可以發佈相關代碼 –