[Ruby] [Rails] How to use Scope

less than 1 minute read

Development environment

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

Basic syntax

class model name< ApplicationRecord
  scope :Scope name, -> {Conditional expression}
end

Example of use

Suppose you want to display only 5 user IDs in descending order as shown below.

users_controller.rb


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

1. No arguments

models/user.rb


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

users_controller.rb


User.recent

2. With arguments

models/user.rb


class User < ApplicationRecord
  scope :recent, -> (count) { order(id: :desc).limit(count) }
end

users_controller.rb


User.recent(5)