Search code examples
ruby-on-railsrubyrails-activerecordrails-consoleruby-on-rails-5.1

Why 'ApplicationRecord.descendants.count' gives 1 even there are many descendants (inheriting models) of ApplicationRecord?


I ran following code in rails console:

ApplicationRecord.descendants.count # 1 = this gave only 1

Even there are many child classes inheriting from "ApplicationRecord" class insde project_root/app/models/ in rails 5.1.3.


Solution

  • This is because your models are not load. They are loaded by Rails autoloader the first time they are invoked.

    For example, if you have a User model:

    > ApplicationRecord.descendants.count
    => 1
    
    > User.count # You can also run User.last or something different 
    => 144 # The result doesn't mind
    
    > ApplicationRecord.descendants.count
    => 2 # It can be a different number but it will be bigger