Are Rails scope and class method different?

Post by Lưu Đại at 29-02-2024
My answer is they're not different. Scope is a special class method. 

So why scope can always chain but class method is not ? 

In order to chain class method we need to make each chained method return an object that contains all other methods of the original class.
Let's test to see what a scope return
71_1.png
So it returns a Post::ActiveRecordRelation, this is a class that created automatically when class Post extend ActiveRecord::Base. More specific the code to create that class written in Delegation::DelegationCache module.
71_2.png
When class X::ActiveRecordRelation is created, it will be created inside original model namespace. For example above it's Post.
The methods of original model class will be imported after X::ActiveRecordRelation is created. If the original model has parent class the methods of parent class will also be imported and so on. Note that the parent class's methods will be imported after the original class.
71_3.png
So as long as the return object is ActiveRecord::Relation the class methods can be chained 😉

Why do we need both scope and class method?

Because of ruby on rails rule: "Convention over configuration" scope and class methods is separated for differentiate it's purpose of use.
For more information about when should we use class methods and when should we use scopes there's a blog about it Should You Use Scopes or Class Methods?