has_many通过使用错误的列

时间:2018-02-12 14:24:23

标签: ruby-on-rails

我是一个简单的rails应用程序。它包含两个模型。 Employee和EmployeeManager。我基本上希望员工有一个或多个经理(其他员工),我希望能够像您期望的那样查询这些经理。

这是我的员工:

class Employee < ActiveRecord::Base
  attr_accessible :name
  has_many :employee_managers
  has_many :managers,  through: :employee_managers
  has_many :employees, through: :employee_managers
end

经理模特:

class EmployeeManager < ActiveRecord::Base
  attr_accessible :employee_id, :manager_id
  belongs_to :employee, foreign_key: "employee_id"                                                                                                        
  belongs_to :manager, class_name: "Employee", foreign_key: "manager_id"
end

这对我来说没问题,但是当我去查询员工和经理时,员工Rails使用的是同一列(employee_id = X):

IRB(主):008:0&GT; Employee.first 员工负荷(0.3ms)SELECT&#34;员工&#34;。* FROM&#34;员工&#34;限制1 =&GT; #
IRB(主):009:0&GT; Employee.first.managers
员工负担(0.1ms)SELECT&#34;员工&#34;。* FROM&#34;员工&#34; LIMIT 1员工负荷(0.1ms)SELECT&#34;员工&#34;。* FROM&#34;员工&#34; INNER JOIN&#34; employee_managers&#34; ON&#34;员工&#34;。&#34; id&#34; =&#34; employee_managers&#34;。&#34; manager_id&#34;在哪里&#34; employee_managers&#34;。&#34; employee_id&#34; = 1 =&GT; []
IRB(主):010:0&GT; Employee.first.employees
员工负荷(0.4ms)SELECT&#34;员工&#34;。* FROM&#34;员工&#34; LIMIT 1员工负担(0.3ms)SELECT&#34;员工&#34;。* FROM&#34;员工&#34; INNER JOIN&#34; employee_managers&#34; ON&#34;员工&#34;。&#34; id&#34; =&#34; employee_managers&#34;。&#34; employee_id&#34; WHERE&#34; employee_managers&#34;。&#34; employee_id&#34; = 1 =&GT; []

如何修复此最后一个查询?它应该使用manager_id而不是employee_id!

提前致谢:)

1 个答案:

答案 0 :(得分:1)

在Employee模型中设置foreign_key,并添加和反向关系(它的模型相同)

class Employee < ActiveRecord::Base
  has_many :employee_managers
  has_many :managers, through: :employee_managers

  has_many :manager_employees, :class_name => "EmployeeManager", :foreign_key => "manager_id"
  has_many :employees, through: :manager_employees, :source => "Employee"
end

其他变化:

您不需要attr_accessible :nameattr_accessible :employee_id, :manager_id。只需为不在数据库中的字段添加attr_accessible。