0
votes

I've a simply rails application. It contains two models. Employee and EmployeeManager. I Basically want an Employee to have one or more Managers (other Employees) and I wish to be able to query these as you would expect.

Here's my Employee:

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

And the manager model:

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

This looks OK to me, however when I go to query employees and managers off an Employee Rails is using the same column (employee_id=X):

irb(main):008:0> Employee.first Employee Load (0.3ms) SELECT "employees".* FROM "employees" LIMIT 1 => #
irb(main):009:0> Employee.first.managers
Employee Load (0.1ms) SELECT "employees".* FROM "employees" LIMIT 1 Employee Load (0.1ms) SELECT "employees".* FROM "employees" INNER JOIN "employee_managers" ON "employees"."id" = "employee_managers"."manager_id" WHERE "employee_managers"."employee_id" = 1 => []
irb(main):010:0> Employee.first.employees
Employee Load (0.4ms) SELECT "employees".* FROM "employees" LIMIT 1 Employee Load (0.3ms) SELECT "employees".* FROM "employees" INNER JOIN "employee_managers" ON "employees"."id" = "employee_managers"."employee_id" WHERE "employee_managers"."employee_id" = 1 => []

How do I fix this last query? It should be using manager_id not employee_id!

Thanks in advance :)

1

1 Answers

1
votes

Set the foreign_key in the Employee model, and add and inverse relation (its the same Model)

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

Other changes:

You don't need attr_accessible :name or attr_accessible :employee_id, :manager_id. Just add attr_accessible for fields that are not in the database.