0

guides.rubyonrails.com を見ると、自己結合の構文が表示されます。

class Employee < ActiveRecord::Base
  has_many :subordinates, :class_name => "Employee",
    :foreign_key => "manager_id"
  belongs_to :manager, :class_name => "Employee"
end

私がやりたいことは、次のようなものです:

class Project < ActiveRecord::Base
  has_many :workers, :class_name => "Employee",
    :foreign_key => "manager_id"
  belongs_to :manager, :class_name => "Employee"
end

または、関係をポリモーフィックに定義することもできます。

class Project < ActiveRecord::Base
  belongs_to :manager, :polymorphic => true
  has_many :employees
end

class Employee < ActiveRecord::Base
  has_many :projects, :as => :manager
end

だから私が探している関係はHABTMのようなものだと思いますが、持つことと所属することの間に明確な違いがあります. 何か案は?

4

1 に答える 1

2

簡単に言えば、マネージャーには多くのプロジェクトがあり、各プロジェクトには多くのワーカーがあります。右?もしそうなら:

class Project < ActiveRecord::Base
  belongs_to :manager, :class_name => 'Employee', :foreign_key => 'manager_id'
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :project
  has_many :managed_projects, :class_name => 'Project', foreign_key => 'manager_id'
  scope :managers, includes(:managed_projects).where('manager_id IS NOT NULL).order('NAME ASC')

end

これにより、従業員はプロジェクトで同時にマネージャーとワーカーの両方になることができます (多層プロジェクトの場合など)。

#The projects of the first manager (managers sorted by name) 
Employee.managers.first.project

# The workers (Employees) working on the project with id 1
Project.find(1).workers

# The manager (Employee) of the project with id 1
Project.find(1).manager

#Employees that are both Workers and Managers (left as an exercise)
Employee.workers_and_managers

関係を試みるもう 1 つの方法は、STI (単一テーブル継承) を使用することです。この場合、フィールド名の「タイプ」によって、従業員がワーカーかマネージャーか (相互に排他的) が決定されます。

class Employee < ActiveRecord::Base
  #table Employees includes 'type' field
end

class Worker < Employee
  belongs_to :project
end

class Manager < Employee
  has_many :projects
end

今 - あなたができること:

Manager.create(:name => 'John Doe') 
#you don't have to specify type - Rails will take care of it

#Find Projects managed by Employee with id 1
Manager.find(1).projects

#Find the project the Employee with id 2 is working on
Worker.find(2).project

#Find the manager of Project with id 1
Project.find(1).manager

#Find workers of Project with id 1
Project.find(1).worker
于 2012-11-04T05:30:03.067 に答える