[RUBY] [Rails] How to use Scope

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)

Recommended Posts

[Rails] How to use Scope
[Rails] How to use enum
[Rails] How to use enum
How to use rails join
[Rails] How to use validation
[Rails] How to use "kaminari"
[Rails] How to use gem "devise"
How to use scope (JSP & Servlet)
[Rails] How to use devise (Note)
[Rails] How to use flash messages
How to use Ruby on Rails
[Rails] How to use Active Storage
[Introduction to Rails] How to use render
How to use Map
How to use custom helpers in rails
How to write Rails
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
[Rails] How to use rails console with docker
How to use map
[Rails] How to use ActiveRecord :: Bitemporal (BiTemporalDataModel)
[Rails] How to use the map method
How to use collection_select
How to use Twitter4J
How to use MapStruct
How to use MySQL in Rails tutorial
How to use hidden_field_tag
How to use TreeSet
How to uninstall Rails
How to use identity
How to use hashes
How to use JUnit 5
[Ruby on Rails] How to use redirect_to
[Note] How to use Rails 6 Devise + cancancan
[Ruby on Rails] How to use kaminari
How to use Dozer.mapper
How to use Gradle
[Rails] How to use video_tag to display videos
[Rails] How to use helper method, confimartion
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use credentials.yml.enc introduced in Rails 5.2
How to use Map
[Rails] How to use select boxes in Ransack
How to use rails g scaffold, functions, precautions
How to use scope and pass processing (Jakarta)
How to use JQuery in js.erb of Rails6
[Ruby on Rails] How to use session method
[Rails] How to use PostgreSQL in Vagrant environment
Rails scope anti-patterns and how to eliminate them
[Java] How to use Map
[rails] How to post images
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
How to use java Optional
How to use Ruby return