Alex Rivera | Logout

Rails STI association with subclasses

Asked 2012-06-20T11:21:05.817
8

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'
end

class User < ActiveRecord::Base
end

class User::Employee < User
  belongs_to :branch
end

class User::BranchAdmin < User::Employee
end

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

Branch.first.employees.count
=> 2

Branch.first.admins.count
=> 1

Branch.first.employees.count
=> 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'
end

since they all be found from their branch_id but this creates problems in the controller if I want to do branch.employees.build then the class will default to User 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', 
    finder_sql: Proc.new{
      %Q(SELECT users.* FROM users WHERE users.type IN          ('User::Employee','User::BranchAdmin') AND users.branch_id = #{id})
    },
    counter_sql: Proc.new{
      %Q(SELE
Edit
Report

1 Answer

2

Can you use :conditions?

class Branch < ActiveRecord::Base
   has_many :employees, class_name: 'User::Employee', :conditions => {:type => "User::Employee"}
   has_many :admins, class_name: 'User::BranchAdmin', :conditions => {:type => "User::BranchAdmin"}
end

This would be my preferred method. One other way to do it might be to add a default scope to the polymorphic models.

class User::BranchAdmin < User::Employee
  default_scope where("type = ?", name)
end
answered 2012-09-20T22:04:21.667

Your Answer