・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
class model name< ApplicationRecord
scope :Scope name, -> {Conditional expression}
end
Suppose you want to display only 5 user IDs in descending order as shown below.
users_controller.rb
User.order(id: desc).limit(5)
models/user.rb
class User < ApplicationRecord
scope :recent, -> { order(id: :desc).limit(5) }
end
users_controller.rb
User.recent
models/user.rb
class User < ApplicationRecord
scope :recent, -> (count) { order(id: :desc).limit(count) }
end
users_controller.rb
User.recent(5)
Recommended Posts