技術ブログ

(技術系中心)基本自分用備忘録なので、あくまで参考程度でお願いします。

Scopeが便利

Scopeが便利

カスタム用のクエリを作成する時にはscopeが便利

Class hoge < Application:Record
.
.
.
  belongs_to :user

  scope :recent, -> {order(created_at: :desc)}
.
.
.
①hoge = Hoge.recent
②hoge = Hoge.recent.first
③hoge = Hoge.recent.last

①全件数を新しい順に獲得 ②最も新しいユーザーを取得 ③最も古いユーザーを取得