Ruby on rails 使用STI加载ActiveRecord

Ruby on rails 使用STI加载ActiveRecord,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有这种情况 模型A 从A继承的模型B和C C有一个指向B的属性parent_id B的父id属性为零 B和C都有特殊的用户 C的特殊用户是其拥有的特殊用户和B的特殊用户 现在我最初把这种关系表述为 # in C belongs_to :B, class_name: "B", foreign_key: "parent_id", inverse_of: :schools has_many :own_special_users, -> { User.special_users }, throu

我有这种情况

  • 模型A
  • 从A继承的模型B和C
  • C有一个指向B的属性parent_id
  • B的父id属性为零
  • B和C都有特殊的用户
  • C的特殊用户是其拥有的特殊用户和B的特殊用户
  • 现在我最初把这种关系表述为

    # in C
    belongs_to :B, class_name: "B", foreign_key: "parent_id", inverse_of: :schools
    has_many :own_special_users, -> { User.special_users }, through: :users
    has_many :parent_special_users, through: :district, source: :special_users
    
    def special_users
      own_special_users + parent_special_users
    end
    
    这就是B的样子

    # in B
     has_many :cs, class_name: "C", foreign_key: "parent_id"
    
      has_many :special_users, -> { User.special_users }, through: :special_users
    
    这就是A的样子

    # in B
     has_many :cs, class_name: "C", foreign_key: "parent_id"
    
      has_many :special_users, -> { User.special_users }, through: :special_users
    
    现在这个成功了!然而,这种方法不起作用。我之所以知道这一点是因为当我知道的时候

    ActiveRecord::Associations::Preloader.new.preload(instances_of_a, [:special_users])
    
    通过rails控制台中的ActiveLogger,没有执行任何操作(我认为这意味着预加载程序实际上没有执行SQL?-我是ActiveRecord新手)。我也知道它不起作用,因为我有perf测试来计算执行的sql查询的数量,并且我在任何地方都有额外的更改(查看堆栈跟踪)

    我确实认为,因为预加载以前起过作用,所以最好只在一段时间内表达这种关系

    所以我有两个问题

  • 为什么预加载/预加载不适用于我表达的关系
  • 我怎样才能用一种简单的语言表达上述内容
  • 谢谢-如果不清楚也请告诉我-我知道这很复杂,可能需要更多的上下文