You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: guides/source/autoloading_and_reloading_constants.md
+28-2Lines changed: 28 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -314,19 +314,45 @@ Single Table Inheritance is a feature that doesn't play well with lazy loading.
314
314
315
315
In a sense, applications need to eager load STI hierarchies regardless of the loading mode.
316
316
317
-
Of course, if the application eager loads on boot, that is already accomplished. When it does not, it is in practice enough to instantiate the existing types in the database, which in development or test modes is usually fine:
317
+
Of course, if the application eager loads on boot, that is already accomplished. When it does not, there are two options.
318
+
319
+
### Enumerate the leaves of the hierarchy
320
+
321
+
Since the leaves of the hierarchy connect all the hiearchy nodes upwards, following super classes, as soon as the root of the hierarchy is loaded, you can force loading them all:
322
+
323
+
```ruby
324
+
unlessRails.application.config.eager_load
325
+
Rails.autoloaders.main.on_load("RootSTIModel") do
326
+
Leaf1
327
+
Leaf2
328
+
Leaf3
329
+
end
330
+
end
331
+
```
332
+
333
+
This approach is easy and loads the entire STI hierarchy, but you need to maintain this list by hand. This may be OK.
334
+
335
+
### Load what's in the database
336
+
337
+
As far as Active Record is concerned, in practice it may be enough to load what's in the database. Normally, in the environments where eager load is disabled, you can afford this query:
318
338
319
339
```ruby
320
340
# config/initializers/preload_stis.rb
321
341
unlessRails.application.config.eager_load
322
342
Rails.autoloaders.main.on_load("RootSTIModel") do |klass|
This approach does not need manual maintenance. However, if you need an exhaustive enumeration to fill a dropdown or something, and the database does not have rows for all types, you'll miss some.
0 commit comments