Environment
Ruby: 1.9.2-p136
Rails: 3.0.4
Situation
Create project with STI for Users and inherit one type of User
(Support) to another types (Administrator, Employee)
Models
#app/models/user.rb
class User < ActiveRecord::Base
end
#app/models/support.rb
class Support < User
end
#app/models/administrator.rb
class Administrator < Support
end
#app/models/employee.rb
class Employee < Support
end
Migration
#db/migrate/20110225123900_create_users.rb
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :type
end
end
def self.down
drop_table :users
end
end
Console
Create instances of Administrator and Employee:
> Administrator.create
> Employee.create
Now get them(Support's users) using Support.all.
> Support.all
=> [#<Administrator id: 1, type: "Administrator">, #<Employee id: 2, type: "Employee">]
Now we reload environment and check Support.all again. And get
this bug!
> reload!
> Support.all
=> []
Difference in SQL command
Before reload!
SELECT `users`.* FROM `users` WHERE (((`users`.`type` = 'Support' OR `users`.`type` = 'Administrator') OR `users`.`type` = 'Employee')
After reload!
SELECT `users`.* FROM `users` WHERE (`users`.`type` = 'Support')
Workaround
We can temporary repair it by using before method #all for
parent class User:
> User.all
=> [#<Administrator id: 1, type: "Administrator">, #<Employee id: 2, type: "Employee">]
> Support.all
=> [#<Administrator id: 1, type: "Administrator">, #<Employee id: 2, type: "Employee">]