[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 authenticate_user!
[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 write Rails
How to use rbenv
How to use with_option
How to use fields_for
How to use java.util.logging
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 active_hash! !!
How to use MapStruct
How to use TreeSet
How to uninstall Rails
[How to use label]
How to use hashes
[Ruby on Rails] How to use redirect_to
[Note] How to use Rails 6 Devise + cancancan
[Rails] How to use video_tag to display videos
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
How to use rails g scaffold, functions, precautions
How to use JQuery in js.erb of Rails6
[Rails] How to use PostgreSQL in Vagrant environment
[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
How to read rails routes
How to use @Builder (Lombok)
How to use Big Decimal
[Java] How to use removeAll ()
How to use String [] args
How to use Java Map
Ruby: How to use cookies
How to use Eclipse Debug_Shell
How to use Apache POI
How to terminate rails server
How to write Rails seed
[Rails] How to disable turbolinks
How to use GC Viewer
[Rails] How to implement scraping
[Rails] How to make seed