Dynamically loadable STI classes

Scenario: There are several STI models in my Rails 3.2 application. Sometimes I use parent classes to query databases for child classes, as shown below:

class ParentObject < ActiveRecord::Base end class ChildObject < ParentObject end class User < ActiveRecord::Base has_many :parent_objects end > User.find(1).parent_objects => [#<ParentObject ...>, #<ChildObject ...>] 

If I check the generated SQL query, then what I (expected) see:

 WHERE "parent_objects"."type" IN ('ParentObject', 'ChildObject') 

Problem: when in the development environment, classes are dynamically reloaded on change. If I changed something to ParentObject and did not restart the Rails console, then instead we get:

 > User.find(1).parent_classes => [#<ParentObject ...>] 

Check generated SQL:

 WHERE "parent_objects"."type" IN ('ParentObject') 

But:

 > ChildObject => ChildObject(...) > User.find(1).parent_objects => [#<ParentObject ...>, #<ChildObject ...>] 

Question: where in my Rails application can I write a small piece of code that will reload any STI models for each web server request?

+4
source share
2 answers

I found a solution ...:

 # in development.rb ActionDispatch::Reloader.to_prepare do Rails.application.eager_load! end 
+3
source

One solution is to create a filter on the ApplicationController:

 class ApplicationController < ActionController::Base before_filter :reload_sti_classes if Rails.env.development? def reload_sti_classes [ParentObject, ChildObject] end end 

It seems to me wrong.

0
source

All Articles