Subclasses of ActiveRecord Model Not Displayed

Here is the trivial inheritance (STI):

class Parent < ActiveRecord::Base
end 

class Daughter < Parent
end

class Son < Parent
end

Quick try in console. Expecting Parent.subclassesto return two subclasses, but having received nothing!

ruby-1.9.2-p0 > Parent.subclasses
 => [] 



Also causing

ruby-1.9.2-p0 > Daughter.subclasses
 => [] 

which correctly returns no children, makes the parent start recognize the daughter as a subclass:

ruby-1.9.2-p0 > Parent.subclasses
 => [Daughter(id: integer, type: string, created_at: datetime, updated_at: datetime)] 

The same thing works for another subclass:

ruby-1.9.2-p0 > Son.subclasses
 => [] 
ruby-1.9.2-p0 > Parent.subclasses
 => [Daughter(id: integer, type: string, created_at: datetime, updated_at: datetime), Son(id: integer, type: string, created_at: datetime, updated_at: datetime)] 

These are rails 3, but the same behavior appears on 2.3.10

+3
source share
2 answers

This is a known issue.

One workaround is to register subclasses at the bottom of the base class file.

%w(daughter son).each {|r| require_dependency r } if Rails.env.development?
+5
source

, . , . cache_classes = true , . , .

+1

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


All Articles