Scopeについて

技術ブログなんて大層なものでは無いけど、Qiitaとかに投稿する程でも無い事をアウトプットがてら、ここにメモっていこうと思う。

(基本構文)

scope :scope名, -> { sql文 }  

RailsでScopeを使う際のポイント

Controller内でクエリが増えすぎたり、メソッドチェーンを繋ぎすぎて見えずらくなった場合は、scopeにまとめた方が良いらしい。

class ProductsController < ApplicationController
  def index
  @products = Product.joins(:place).where(main_area:"US",mini_area:"DC")
  end
end
class Product < ApplicationRecord
  scope :includes_city,-> {joins(:place)}
  scope :search_with_id, ->(area_id) { where(id: area_id)}
end

引数も取れるしメソッドチェーンも使える。

Product.includes_city.search_with_id(2)

 あとはもちろん、クラスメソッド定義でも可能。🐤