LoginSignup
0
0

More than 1 year has passed since last update.

whereやorderをモデルのscopeで書く方法

Posted at

先日レビューで先輩エンジニアに教えてもらったことが勉強になったので備忘兼ねて投稿します。
whereやorderなどを使うときはモデルのscopeとして書くとスッキリするのと、使い回しもできて良いみたいです。

controllerに書く方法

今回は商品(products)テーブルで開発日(development_date)降順で並べるとします。

products_controller.rb
def index
  @products = Product.order(development_date: :desc)
end

modelのスコープとして書く方法

まずモデルに以下のようにscopeを定義します。

product.rb
scope: :development_order, -> { order(development_date: :desc) }

コントローラで呼び出します。

products_controller.rb
def index
  @products = Product.development_order
end

このようにすることで、コントローラがスッキリし、複雑な条件の時にscope名からどんな処理をしているのかを推測しやすかったり、別の箇所で使うときに再利用できたりするメリットがあります。

0
0
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
0
0