データーベースから検索した条件を、ビューに表示したい時・・・
products_controller.rb
class ProductsController < ApplicationController
def index
parent = Category.find(1)
child = Category.where( parent_id: parent.id )
grandchild = Category.where( parent_id: child.ids )
@ladies = Product.where(category_id: grandchild ).order(created_at: :DESC).limit(4)
end
end
こんな感じに長くなってしまう時があります。
しかも
products_controller.rb
parent = Category.find(1)
parent = Category.find(3)
parent = Category.find(5)
と条件が増えるとcontroller
の可読性が下がり、他の開発者がわかりずらい時があります。
こんな時は・・・検索条件をmodel
に作成します。
scopeの使い方の詳細はこちらを参考にしてください。
今回私がやりたかった事は、
productsテーブルの中にある商品をカテゴリごとに表示する事。
product.rb
class Product < ApplicationRecord
scope :recent_category, lambda { |count|
parent = Category.find(count)
child = Category.where( parent_id: parent.id )
grandchild = Category.where( parent_id: child.ids )
where(category_id: grandchild ).order(created_at: :DESC).limit(4)
}
scope :recent_brand, lambda { |count|
where(brand_id: count ).order(created_at: :DESC).limit(4)
}
end
今回カテゴリーは自己結合で作成しているため、productsテーブルのcategory_id
は孫idとなっています。
where(category_id: 親id )
ではデータを取得できません。
なので、まず親idから孫ids(複数あるのでsをつけています)を取得する必要があります。
product.rb
parent = Category.find(count)
child = Category.where( parent_id: parent.id )
grandchild = Category.where( parent_id: child.ids )
この方法で孫idsを取得しました。
今回( )の部分がカテゴリーによって値が変わるため、引数として値を渡しています。
product.rb
scope :recent_category, lambda { |引数|
parent = Category.find(引数)
}
controllerで、scopeの変数を記述して値を渡してあげれば・・・
products_controller.rb
class ProductsController < ApplicationController
def index
@ladies = Product.recent_category(1)
@mens = Product.recent_category(2)
@babys = Product.recent_category(3)
@goods = Product.recent_category(4)
@Vuittons = Product.recent_brand(44)
@chanerls = Product.recent_brand(42)
@nikes = Product.recent_brand(143)
@syupus = Product.recent_brand(125)
end
end
検索条件のテンプレートを作成する事ができ、あら、スッキリーなcontrollerの出来上がり!
⚠️初心者為色々と間違っている箇所があるかと思います。
お気がつきになられましたら、コメントいただけますと勉学の励みになります。
何卒よろしくお願いいたします。