I've code like this
x_data = Model.where(column: 'xyz')
and I wanted to use 'x_data' everywhere like models, controllers,
I used in this way
X_DATA = Model.where(column: 'xyz')
but when using Global::X_DATA it is firing query every time.
Where should I write this to use it everywhere and query should not be
fired more than once.
add this in initializers is a good practice?
Thanks in advance.
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:
@all_admin_users ||= self.where(role: ‘admin’)
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.
or provide any useful links