2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】Scopeの使い方

Posted at

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

基本構文

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

使用例

下記のようユーザーのIDを降順にして5つだけ表示させたいと仮定します。

users_controller.rb
User.order(id: desc).limit(5)

1.引数なし

models/user.rb
class User < ApplicationRecord
  scope :recent, -> { order(id: :desc).limit(5) }
end
users_controller.rb
User.recent

2.引数あり

models/user.rb
class User < ApplicationRecord
  scope :recent, -> (count) { order(id: :desc).limit(count) }
end
users_controller.rb
User.recent(5)
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?