STI Initiative in Rails. Search problems

I am having a problem finding 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 find doesn't work for AuthUser Model. The query looks for the type "AuthUser" and does not include the other three possibilities.

Edit: While playing with it, it started working, but only for ClientAdmin and FieldUser, so it seems like this functionality should be built in, but now it's back to the original issue

+2


source to share


3 answers


I just ran into this problem and found the solution here .

In short, the problem is that your intermediate abstract class doesn't know what its subclasses are before loading. To work around this, you can manually load all subclasses at the bottom of that class file.



So at the bottom of the auth_user.rb file:

require_dependency 'super_user'
require_dependency 'field_user'
require_dependency 'client_user'

      

+3


source


Will the AuthUser model be used by itself?

If it is just a class for common methods between inherited classes, you can try to set it as an abstract class. This way ActiveRecord can go through it.

In your AuthUser declaration, just add self.abstract_class = true

like this:



class AuthUser < User
     self.abstract_class = true
end

      

I don't know if it works in this scenario, but it might be worth trying.

+2


source


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 described above: I think you are limited to one level of the hierarchy.

0


source







All Articles