0
0

More than 1 year has passed since last update.

scope

Posted at

scopeとは

Railsのスコープ機能を利用するためのメソッド。
スコープ機能というのは、クエリを定義することができる機能で、何度も同じクエリを使うような場合に、メンテナンス性を上げることができる。

◆出来ること
・並べ替えや絞り込みを行う
・クエリを定義して使い回す

クエリとは?
 データベースに対する命令文。
 find_by、where、order、limit、distinctなど

scopeの基本構文

class モデル名 < ApplicationRecord
  scope :スコープの名前, -> { 条件式 }
end

定義したスコープは以下のように呼び出す事が出来る
モデル名.スコープ名

例:
class Blog < ApplicationRecord
    scope :published, -> { where(published: true) }
end

Blog.published

参考記事

【Rails入門説明書】scopeについて解説
【Rails】 モデルのスコープ機能(scope)の使い方を1から理解する
クエリメソッドをまとめてみた[Rails]

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