LoginSignup
0

posted at

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

先日レビューで先輩エンジニアに教えてもらったことが勉強になったので備忘兼ねて投稿します。
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名からどんな処理をしているのかを推測しやすかったり、別の箇所で使うときに再利用できたりするメリットがあります。

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
What you can do with signing up
0