问题
I am having an issue with searching for records in my STI table due to my inheritance structure
class User < ActiveRecord::Base
class LegacyUser < User
class AuthUser < User
class SuperUser < AuthUser
class FieldUser < AuthUser
class ClientAdmin < AuthUser
The problem is that find does not work for the AuthUser Model. The query is looking for type "AuthUser" and does not include the other three possibilities.
Edit: While playing around with this it started to work but only for ClientAdmin and FieldUser so it seems this functionality should be build in. but now it has gone back to the original issue
回答1:
I just ran into this same issue and found a solution here.
In short, the issue is that there is no way for your intermediate abstract class to know what its subclasses are before they are loaded. To work around this, you can manually load all the subclasses at the bottom of that classes' file.
So at the bottom of auth_user.rb:
require_dependency 'super_user'
require_dependency 'field_user'
require_dependency 'client_user'
回答2:
Is the AuthUser model going to be used by itself?
If it is only a class for shared methods between the inherited classes you could try to set it as an abstract class. That way ActiveRecord might pass right through it.
In the declaration of AuthUser, just add self.abstract_class = true
like this:
class AuthUser < User
self.abstract_class = true
end
I do not know if that works in this scenario, but it could be worth a try.
回答3:
Due to the way STI works in Rails (it stores the model name in a database column called 'type') I don't see how it can support the hierarchy you describe above - I think you are limited to a single level hierarchy.
来源:https://stackoverflow.com/questions/1296360/sti-inheiritance-in-rails-issues-with-find