[RAILS] I think it's okay to write joins etc. in the scope
It is subjective. I think there are pros and cons, but I would be grateful if you could give us various opinions.
background
I saw this code.
class Hoge
scope :with_active_fuga, -> { merge(Fuga.active) }
With this, the scope alone does not work. You have to add joins (: fuga) etc.
But this joins (: fuga) etc.
- Is it better to add it in the process like
joins (: fuga) .with_active_fuga
?
- Or is it better to add joins (: fuga) etc. to the caller outside the scope?
I was wondering, so I stopped and thought about it.
Reasons for deciding that it is okay to write in scope
- If you go out, there is a risk that the scope designer will use it unintentionally in terms of performance and operation because it entrusts the type of join to the user.
- If you make joins etc. on the premise of going out, you will simply leave the code that does not work as it is.
- Like
joins (: fuga) .joins (: fuga)
, even if the same contents are covered by the combination of scopes, SQL will not be affected.
- Since it can coexist with includes, preload, and eager_load, there is no problem if you want to cache at the same time.
- You may want to choose between inner join and outer join, but this will change the role of processing depending on whether to include cases that are not related to the table, so create each scope It can be judged that it is better to do it.
By the way
Since there are some people who create processing in the class without using scope for narrowing down where joins etc. occur, ** "narrowing down = scope" is not always **.