LoginSignup
1
3

More than 3 years have passed since last update.

【Rails】多階層カテゴリーから商品一覧を表示させるプロセスとは

Posted at

前提条件

以下のことが終わっていることとする。終わっていないと機能が正しくなっているか確認が難しい。
・ancestryを用いてカテゴリーテーブルを作成している。
・カテゴリー:商品 = 1:多の関係になっている。
・カテゴリーの階層が3段階になっておりそれぞれの命名が「親」、「子」、「孫」になっている
・商品モデルのcategory_idには、最下層のカテゴリーidが登録されている。
・gem kaminariがインストール済
・カテゴリーコントローラーファイルの作成及び、カテゴリーの取得ができるコードが書かれている。

不安な人はここをクリック
以下のようなコードが書かれていれば、問題ない。
_Rails_多階層カテゴリーから商品を検索・一覧表示する機能_-_Qiita.png
_Rails_多階層カテゴリーから商品を検索・一覧表示する機能_-_Qiita.png

カテゴリー別に商品一覧を表示させる

カテゴリーの詳細が見たいわけなのでshowアクションを用います。

showアクション定義

app/controllers/categories_controller.rb

before_action :set_category, only: :show

def show
  @items = @category.set_items
  @items = @items.where(buyer_id: nil).order("created_at DESC").page(params[:page]).per(9)
end

private
def set_category
  @category = Category.find(params[:id])
end

モデルメソッド定義

app/models/category.rb

has_many :items
has_ancestry

def set_items
  # 親カテゴリーだった場合
  if self.root?
    start_id = self.indirects.first.id
    end_id = self.indirects.last.id
    items = Item.where(category_id: start_id..end_id)
    return items

    # 子カテゴリーだった場合
  elsif self.has_children?
    start_id = self.children.first.id
    end_id = self.children.last.id
    items = Item.where(category_id: start_id..end_id)
    return items

    # 孫カテゴリーだった場合
  else
    return self.items
  end
end

@items = @category.items と記述するだけでは、
商品モデルのcategory_idには最下層のidが付与されているので@categoryが孫であった場合のみ、情報が取得されることになってしまう。
なので予め、上記のようにカテゴリーが親なのか子なのか孫なのかといったような条件分岐をするとうまくいくはず

ビュー

app/views/categories/show.html.haml

.items-container
  .items-index
    .title
      = "#{@category.name}の商品一覧"
      .title__border
    - if @items
      %ul.lists
        = render "items/item", items: @items
    = paginate @items

このままでは他のカテゴリーへのリンクがまだ設定されていないが、
それはまた、書いていきます

1
3
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
1
3