簡體   English   中英

Rails子類別

[英]Rails subcategories

如何查找和管理子類別? (我定義的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 gem,它有:

 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

目前還不清楚你想要find_subcategory方法做什么,但如果你想讓它找到id為params [:id]的類別的所有子類別,那么將它改為

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

在您的原始版本中,您只需要查找單個子類別,如果您只想要一個類別,那么您也可以從它的id中加載它。

我知道你接受了答案,但我之前已經這樣做了 ,所以解釋我們是如何做到的可能是有益的:


首先,我們使用了祖先寶石。 我認為acts_as_tree已被棄用 - acts_as_treeancestry更好,我忘了為什么我們現在使用它 - ancestry非常類似的方式工作( parent列, child方法等)。

我將用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 )列,並且(最重要的)使您能夠調用附加到模型中對象child方法

@category.parent
@category.children

...等

-

這里要注意的重要一點是我們如何調用child對象(在您的情況下將是子類別 )。

您的方法是創建單獨的對象並讓它們相互繼承。 ancestry / acts_as_tree的美麗是他們增加的方法。

具有正確parent ID的任何對象都可以將其“子”稱為關聯數據:

在此輸入圖像描述

在我們的例子中,我們能夠使用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? %>

這將為您輸出子類別:

在此輸入圖像描述


如何查找和管理子類別

你可以這樣做:

@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 %>

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM