Rails STI and layered inheritance requests

In my database, I have a people table, and I use univariate inheritance with these classes:

 class Person < ActiveRecord::Base end class Member < Person end class Business < Member end 

Problem demonstration

The requests that it begets confuse me. I want Member.all return all Enterprises, as well as any other Member subtypes. What does he do, but only if I recently turned to the business class. I suppose because my classes are not cached in design mode (for obvious reasons), but still seems like weird / erroneous behavior.

Is this a mistake in the rails? Or is he working as intended? In any case, can anyone think of a good development solution?

+5
source share
2 answers

This intentional behavior - the official Rails autoload and constant reloading guide explains this pretty well in the Startup and STI section:

...

The way to ensure proper operation regardless of the execution order is to load the tree leaves manually at the bottom of the file that defines the root class:

 # app/models/polygon.rb class Polygon < ApplicationRecord end require_dependency 'square' 

You need to load only those leaves that, at least, are the grandchildren of the path. Direct subclasses do not require preloading. If the hierarchy is deeper, intermediate classes will automatically load from the bottom, because their constant will appear in the class definitions as a superclass.

So, in your case, this would mean putting require_dependency "business" at the end of your Person class.

However, be careful with circular dependencies that can be avoided by using require instead of require_dependency (even if it can prevent Rails from monitoring and reloading your files when changes are made - after all, require_dependency is Rails-internal).

+2
source

By default, Rails does not want to load your classes during development. Try changing the following line in config/environments/development.rb :

 # Do not eager load code on boot. config.eager_load = false 

in

 # Do eager load code on boot! config.eager_load = true 
+3
source

Source: https://habr.com/ru/post/1233212/


All Articles