Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In layman terms - A Manager would have many Projects, each Project would have many Workers. Right? If so:</p> <pre><code>class Project &lt; ActiveRecord::Base belongs_to :manager, :class_name =&gt; 'Employee', :foreign_key =&gt; 'manager_id' has_many :employees end class Employee &lt; ActiveRecord::Base belongs_to :project has_many :managed_projects, :class_name =&gt; 'Project', foreign_key =&gt; 'manager_id' scope :managers, includes(:managed_projects).where('manager_id IS NOT NULL).order('NAME ASC') end </code></pre> <p>This would allow Employees to be both Managers and Workers in Projects simultaneously (say for multi-tiered projects).</p> <pre><code>#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 </code></pre> <p>Another way of attempting the relation is to use STI (single table inheritance), where a field names 'type' would determine if an Employee is either a Worker or a Manager (mutually exclusive)</p> <pre><code>class Employee &lt; ActiveRecord::Base #table Employees includes 'type' field end class Worker &lt; Employee belongs_to :project end class Manager &lt; Employee has_many :projects end </code></pre> <p>Now - you can do:</p> <pre><code>Manager.create(:name =&gt; '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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload