小编Tom*_*sey的帖子

Rails STI与子类的关联

在使用STI时,从使用rails 3的has_many关联中获取集合时,我遇到了一些奇怪的行为.我有:

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
Run Code Online (Sandbox Code Playgroud)

期望的行为是branch.employees返回所有员工,包括分支管理员.分支管理员在访问它们时似乎只在此集合下"加载" branch.admins,这是从控制台输出的:

Branch.first.employees.count
=> 2

Branch.first.admins.count
=> 1

Branch.first.employees.count
=> 3
Run Code Online (Sandbox Code Playgroud)

这可以在生成的SQL中看到,第一次:

SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee') AND "users"."branch_id" = 1
Run Code Online (Sandbox Code Playgroud)

第二次:

SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee', 'User::BranchAdmin') AND "users"."branch_id" = 1
Run Code Online (Sandbox Code Playgroud)

我只需指定以下内容即可解决此问题:

class Branch < ActiveRecord::Base
   has_many :employees, …
Run Code Online (Sandbox Code Playgroud)

sql activerecord ruby-on-rails sti

7
推荐指数
1
解决办法
8409
查看次数

标签 统计

activerecord ×1

ruby-on-rails ×1

sql ×1

sti ×1