チーム開発 カテゴリ別商品一覧ページ サーバーサイド
今回実装するのは下記ページです。
ヘッダーのプルダウンメニューから、カテゴリ別の商品を一覧で表示するページです。
作業内容
・categories_controller作成
・route記述
・categories_controller編集
・view作成
categories_controllerがなかったので、作成から行いました。
その次にrouteの編集。indexとshowアクションを使いました。
routes.rb
resources :categories, only: [:index, :show]
そのあとviewの作成。
ちょっと頭がこんがらがりそうになりましたが、作成するviewをパーツ分けして、
逆算して組み立てていくことでなんとか形にすることができました。
show.html.haml
= render "top/others/header" .show-wrapper .categories .categories__title = "#{@category.name}の商品一覧" // リンクリスト - if @category_links.present? .categories__links - @category_links.each do |category| .categories__links__link = link_to category.name, category_path(category) -# 商品一覧表示 - if @items %ul.items-list %li = render "top/others/items", products: @items = render "top/introduction/introduction-lower" = render "top/others/footer" = render "top/others/exhibition-btn"
- if @category_links.present?
present?メソッドで出し分け
category_path(category)
idを持たせて再びshowページへとばすパスを指定
categories_controller
before_action :set_category, only: :show before_action :set_category_header, only: [:index, :show] def index end def show @products = @category.set_items @items = @products.where(buyer_id: nil).order("id DESC") end private def set_category @category = Category.find(params[:id]) # カテゴリリンクの出し分け if @category.has_children? @category_links = @category.children else @category_links = nil end end def set_category_header @parents = Category.where(ancestry: nil) end
category.rb
def set_items # 親カテゴリーの場合 if self.root? start_id = self.indirects.first.id end_id = self.indirects.last.id items = Product.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 = Product.where(category_id: start_id..end_id) return items # 孫カテゴリーの場合 else items = Product.where(category_id: self.id) return items end end
なるべくfat modelにしようと思いました^^;