Well, the problem is as follows. I have models hierarchy as follows:
class A < ActiveRecord::Base
end
Class B < A
end
class C1 < B
end
class C2 < B
end
In one of the controllers I need to search for B, C1 or C2.
Rails does it if the related models are loaded.
So the sql query should (and will ideally) contain something like
B.find 224
# => SELECT "bs".* FROM "bs" WHERE "bs"."type" IN ('B','C1','C2') AND "bs"."id" = 224 LIMIT 1
And that the exacly what is needed. However, it turns out that models are unloaded on each request and not loaded again(not sure for reasons of that).
In that case if the models are not in the memory, ActiveRecord will make query like
B.find 224
# => SELECT "bs".* FROM "bs" WHERE "bs"."type" IN ('B') AND "bs"."id" = 224 LIMIT 1
If you will simply call for C1 or C2 before find their types will be included into sql
C1
B.find 224
# => SELECT "bs".* FROM "bs" WHERE "bs"."type" IN ('B','C1') AND "bs"."id" = 224 LIMIT 1
I tried to load those models in the initializers. eval C1, require ‘app/models/c1.rb’, require_dependancy ‘app/models/c1.rb’ but neither of those works. Actually, they all worked for one time. Only one time after server was started. I suspect that there will be no such problem under production environment, but it very annoying.
An Ugly solution is to call C1 and C2 after B definition, in that case it worked as expected, But, as I said already, it is ugly
class B < A
end
C1, C2
Any better Ideas?
Update moved to answer.
Ok, I think I figured out some sort of solution. It is not very impressive, but it seems to be working:
I requires to add a hack to the ActiveSupport::Dependencies.
So here is the hack listing:
And in the initializers a small file to load the hack and to assign an array of constants:
If you have any comments, I would happily listen for them.