That’s actually an interesting question and you need a little knowledge of (1) How actual global variables work in Ruby, and (2) how the Rails boot process works, and (3) How A-Rels (ActiveRelation objects) work under the hood.
Typically what you are trying to do is not actually done. That’s because data in the database changes, so 98% of the time you want the query to re-fire when it goes to look something up. To achieve that (not what you asked for), you typically use a scope on the model.
Caching the result is the next step-up from re-firing each time. That is often done with a memorized method, something like this:
class User
def self.all_admin_users
@all_admin_users ||= self.where(role: ‘admin’)
end
end
But note that even global variables are garbage collected when the current process ends (which in a web scenario is when the response is finished). So that will re-fire on the next web request.
If you truly want to load this in an initializer and have it persist across web requests, then you would indeed do that in an initializer during when the Rails app boots up. But that is rarely useful, since in order to make changes to that data you would have actually restart the entire web process. Generally it’s better just to optimize the query, have it be a memorized method, and let it re-fire on each web request.
Actually it is a static data and it will change rarely may be in 5 or 6
years. That's why I don't want to re-fire it.
If possible could you please brief about (1) How actual global variables
work in Ruby, and (2) how the Rails boot process works, and (3) How
A-Rels (ActiveRelation objects) work under the hood.