You are correct that this is a result of the multi-level hierarchy.
The scope would work as expected if you had just one level of inheritance (i.e. if A
inherited from ActiveRecord::Base
instead of inheriting from O
).
STI in Rails does not always work as expected once you have intermediate classes.
I'm not sure if this is a bug in Rails or just a result of it not being feasible to infer exactly what should be done. I'll have to research that more.
The scope issue you experienced is just one example of the unexpected behavior. Another example is that querying the intermediate class will only query for the class types it is aware of, which may not include all of its subclasses unless you specifically require them:
See the following thread for more information, especially the post at the bottom by MatthewRudy: https://groups.google.com/forum/#!topic/hkror/iCg3kxXkxnA
If you still want to use scopes instead of class methods as suggested by @Atastor, you can put the scope on O
instead of A
. This isn't ideal since the scope may not be applicable to every subclass of O
, but it does seem to cause Rails to query the correct classes in the type
column, and is a quick workaround.