Tom Livesey Tom Livesey - 2 years ago 144
SQL Question

Rails STI association with subclasses

I'm getting some strange behaviour when fetching collections from a has_many association with rails 3 when using STI. I have:

class Branch < ActiveRecord::Base
has_many :employees, class_name: 'User::Employee'
has_many :admins, class_name: 'User::BranchAdmin'

class User < ActiveRecord::Base

class User::Employee < User
belongs_to :branch

class User::BranchAdmin < User::Employee

The desired behaviour is that
returns all employees including branch admins. The branch admins only seem to be 'loaded' under this collection when they have been accessed by
, this is output from the console:

=> 2

=> 1

=> 3

This can be seen in the generated SQL, the first time:

SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee') AND "users"."branch_id" = 1

and the second time:

SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee', 'User::BranchAdmin') AND "users"."branch_id" = 1

I could solve this problem by just specifying:

class Branch < ActiveRecord::Base
has_many :employees, class_name: 'User'
has_many :admins, class_name: 'User::BranchAdmin'

since they all be found from their branch_id but this creates problems in the controller if I want to do
then the class will default to
and I have to hack at the type column somewhere. I have got around this for now with:

has_many :employees, class_name: 'User::Employee',
%Q(SELECT users.* FROM users WHERE users.type IN ('User::Employee','User::BranchAdmin') AND users.branch_id = #{id})
%Q(SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee', 'User::BranchAdmin') AND "users"."branch_id" = #{id})

but I would really like to avoid this if possible. Anyone, any ideas?


The finder_sql and counter_sql haven't really solved it for me because it seems that parent associations don't use this and so
has_many :employees, through: :branches
will again only include the
class in the selection.

Answer Source

Basically, the problem only exists in the development environment where classes are loaded as needed. (In production, classes are loaded and kept available.)

The problem comes in due to the interpreter not having seen yet that Admins are a type of Employee when you first run the Employee.find, etc. call.

(Notice that it later uses IN ('User::Employee', 'User::BranchAdmin'))

This happens with every use of model classes that are more than one level deep, but only in dev-mode.

Subclasses always autoload their parent hierarchy. Base classes don't autoload their child hierachies.


You can force the correct behaviour in dev-mode by explicitly requiring all your child classes from the base class rb file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download