【功能】 usage of scope in rails

  • What is “scope” under Rails?

Scope is a way to simplify ORM (Object-Relational Mapping) language into a packet that’s stationed in the Model, which can then be called for anytime such packet is needed in the Controller.

  • Why do we use scope?

Scope makes it easy to place complex relationships out of the way in the Model to make the Controller clean.

  • How to use scope?

Under the designated Model file, use scope to define a keyword to take on the meaning of the scope, for instance under the post model:

models/post.rb
1
2
3
4
class < ApplicationRecord
scope :recent, -> { order("created_at DESC")}
end

This can then be called for in the controller:

controllers/groups_controller.rb
1
2
3
4
def show
@group = Group.find(params[:id])
@posts = @group.posts.recent
end