如何查找和管理子類別? (我所定義的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
太好了!這正是我的意圖。 – Liroy
只是一個小點。 '.all'在這裏是多餘的。 :-) – Drenmi
@Drenmi有趣的是,我沒有把'.all'放在我原來的答案中,然後我回去添加它,因爲我認爲它更明顯我們想要一個集合而不是單個記錄。 –