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
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
--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