[RUBY] Master the [Rails] scope!

Explanation of scope

Set scope in model and call it with a controller or the like.

-Example- Set scope in User model. Called by the users controller.

app/models/user.rb



class User < ApplicationRecord
  ...
    # scope :Name to call, -> {processing}

    #Get the deleted column is false
    scope :active, -> { where(deleted: false) }
    # created_Get at column in descending order
    scope :sorted, -> { order(created_at: :desc) }
    #A combination of active and sorted
    scope :recent, -> { active.sorted }
  ...
end

app/controllers/users_controller.rb



class UsersController < ApplicationController
  ...
  def index
  # @users =model.scope name

    @users = User.recent
  end
  ...
end

How to use lambda

lambda is an anonymous function. Furthermore, the identity of the anonymous function is a Ruby Proc object. Anonymous functions are, as they are, "unnamed functions". Something like the code below is called an anonymous function. (* Both codes are synonymous.)


nameless_func = lambda { |n| n**2 }
nameless_func.(5)
#=> 25

scope :nameless_func, -> { |n| n**2 }
nameless_func(5)
#=> 25

merit

--By defining the scope of the model, multiple queries can be combined into one method. --If you use scope rather than writing multiple queries in the controller, your code will be cleaner.

Recommended Posts

Master the [Rails] scope!
A note about the scope
Rails ~ Understanding the message function ~
[Rails] Delete the migration file
[Rails] How to use Scope
[Rails] What was the error message?
[Rails] About the Punk List function
[Rails] Check the contents of the object
About the symbol <%%> in Rails erb
Explanation of the order of rails routes
Check the migration status of rails
Scope
[Rails] I tried deleting the application
Check the root on the Rails browser
[rails] The case where the server stopped working
Rails: 7 basic actions defined on the controller
Change the default timezone for the rails app
Item 57 Minimize the scope of local variables
The identity of params [: id] in rails
Try using the Rails API (zip code)
[Rails] How to use the map method
part of the syntax of ruby ​​on rails
Prepare the format environment with "Rails" (VScode)
Rails refactoring story learned in the field
Prepare the security check environment for Rails 6
[Rails] Change the label name of f.label
Check the processing contents with [rails] binding.pry
[Rails] Reset the database in the production environment
Rails6: Extract the image in Action Text