如何查找和管理子类别? (我所定义的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'放在我原来的答案中,然后我回去添加它,因为我认为它更明显我们想要一个集合而不是单个记录。 –