4

Scenario: I have a number of STI models in my Rails 3.2 app. At times, I use parent classes to query the 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 inspect the generated SQL query, that's what I (expectedly) see:

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

Problem: when in development environment, classes are dynamically reloaded when there's changes. If I change something on ParentObject and don't restart the Rails console, that's what I get instead:

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

Inspecting the generated SQL:

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

But:

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

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

Henrique Zambon
  • 1,301
  • 1
  • 11
  • 20

2 Answers2

3

I found the solution...:

# in development.rb
ActionDispatch::Reloader.to_prepare do
  Rails.application.eager_load!
end
BvuRVKyUVlViVIc7
  • 11,641
  • 9
  • 59
  • 111
0

One solution is to create a filter on ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :reload_sti_classes if Rails.env.development?

  def reload_sti_classes
    [ParentObject, ChildObject]
  end
end

It doesn't seem right to me though.

Henrique Zambon
  • 1,301
  • 1
  • 11
  • 20