LoginSignup
2

More than 5 years have passed since last update.

名前付きスコープについての基本的なまとめ rails

Last updated at Posted at 2017-09-16

名前付きスコープとは

特定の条件式や、ソート式などをあらかじめモデル側で名前付けして、利用時には名前で呼び出せるようにしたものです。

例えば、

技術評論社の書籍のみを取得するgihyoスコープ
刊行日の新しい順に並べるnewerスコープ
刊行日の新しい順に10件取得するスコープ

models/book.rb
Class Book < ApplicationRecord
  scope :gihyo, -> { where(publish: '技術評論社') }
  scope :newer, -> { order(published: :desc) }
  scope :top10, -> { newer.limit(10) } 
end

次にコントローラー側からこれを呼び出してみましょう

record_controller.rb
def scope
  @books = Book.gihyo.top10
  render 'hello/list'
end

名前付きスコープに引数を渡す。

models/book.rb
scope :whats_new, ->(pub) {
  where(publish: pub).order(published: :desc).limit(5)
}
Controllers
@books = Book.whats_new('技術評論社')

は以下になる

SELECT "books".*FROM "books" WHERE "books".
"publish" = ? ORDER BY "books" WHERE "books"."published" DESC LIMIT ?
[["publish", "技術評論社"], ["LIMIT", 5]]

default_scope = モデル呼び出しの際にデフォルトで適用されるスコープ

review.rb
Class Review.rb
  default_spope { order(updated_at: :desc) }
end
record_controller.rb
def def_scope
  render plain: Review.all.inspect
end

は以下になる

SELECT "reviews".*FROM "reviews" ORDER BY "reviews"."updated_at" DESC

これらにより綺麗なコードが書けます。

参考書籍「Ruby on Rails5アプリケーションプログラミング」

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
2