4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで多階層カテゴリーの表示方法

Last updated at Posted at 2019-05-13

categoriesテーブル

Column Type Options
name string
pre_category_id integer
pre_precategory_id integer

Assosiation

  • belongs_to :parent, class_name: :Category
  • belongs_to :grand_children, class_name: :Category
  • has_many :children,class_name: :Category, foreign_key: :pre_category_id
  • has_many :grand_children,class_name: :Category, foreign_key: :pre_precategory_id

pre_categoy_idには2段階目が使うように1段階目のidを入れる、それ以外はnil
pre_precategory_idには3段階目が使うように2段階目のidを入れる、それ以外はnil

コンソールコマンドなどで確認

@category =  Category.find(1)
@category.children.grand_children

できちんとnameが取れているか。

controllerにはこれ

@main_categories = Category.eager_load(children: {children: :grand_children}).where('第一階層を取るための検索')

viewにはこう書いた

- @main_categories.each do |main_category|
     工程1
     - main_category.children.each_with_index do |sub_category,i|
        工程2
       - main_category.children[i].grand_children.each do |sub_subcategory|
            - if sub_subcategory.id == sub_category.id

被ると困るところに条件分岐
ブロックはeachには使わない。

一つ一つviewにwhere検索で条件分岐を書いたら昭和のpentiamコンピューターになった。
このやり方ならなんとか見れるレベルの速さに落ち着いた。
headerのカテゴリー分岐にもつかえる、変数はappilication_controllerにbefore_actionで定義する。

書きなぐり

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?