07/09/2018, 16:00

Funny things about Rails scope and class method

When I first read about scope : All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it. That's means : scope is chainable (as far as i understood it) okay, then class method must be different ...

When I first read about scope:

All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it.

That's means : scope is chainable (as far as i understood it)

okay, then class method must be different

Assume that we have a well defined, usable class User

User class had game_id and site_user_id

Let us implement some simple scope and class method in order to test

alt text

OK, we have a scope named scope_game_id and a class method named class_method_game_id with the same purpose: find user by game_id
as shown below
alt text

alt text

okay, now test the CHAINABLE

first the scope

alt text

Oh, it does chaining two conditions together, making one beautiful SQL

How about the class method, I wondering ...

alt text

WHAT THE HECK???

The class method also can chain the conditions together, working exactly the same with scope

okay, Let do some mini test

  • nil input?

alt text

nope....

  • scope allow error input while class method doesnt ?

alt text

no luck ...

  • output nil

alt text

Well...

So what is the true purpose of SCOPE ???

maybe, scope's purpose is just for FUN, make source code looks better ?

u're kidding me?

Luckily, I run the lastest test
Actually I had some chances in my code by adding .first

alt text

alright, one more time

alt text

the class method gives an nil result

how 'bout the scope

alt text

wow, how come it still output records ?

If we take a closer look, after the main logic query, scope automatically check the result, if the result is nil , the magic appears

SELECT `users`.`*` FROM `users` ORDER BY `users`.`id` ASC LIMIT 1

and of course with the help of magic, there will be no nil

So the CHAINING does makes sence here...

The chaining cant to continue if there is a broken chain

Scope will make sure the broken chain wont exist by return all the records when the searching result is nil while class method won't

This make scope a really useful feature , but BE CAREFUL using it

Actually, I had to fix a bug today, so I accidentally found this interested.Before that, I doesnt really care about these things.
And I means it

BE CAREFUL using it

but why has to be careful ?
because of the bug?
I dont really think so...there are things more annoying than the bugs

okay, I will do an research on "Where and When to use scope and class method before I can tell anything about that...

See you in the next part.

0