Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails associations with the same models

I have two classes with the following associations:

class Incident
  has_one :assignee
  has_one :technician

class User 
  has_many :incidents

Note that the assignee and technician fields refer to objects of type User. How should these relationships be in the model?

like image 213
Mercurious Avatar asked Dec 30 '22 02:12

Mercurious


1 Answers

Presumably the Incident should belong_to an assignee and technician, because the foreign key holding those relationships would be in the incidents table, not the employees table

class Incident
  belongs_to :assignee, :class_name => 'User'
  belongs_to :technician, :class_name => 'User'

class User 
  has_many :assigned_incidents, :class_name => 'Incident', :foreign_key => 'assignee_id'

  # not sure the wording you'd want to use for this relationship
  has_many :technician_incidents, :class_name => 'Incident', :foreign_key => 'technician_id'

You would want the foreign key fields to be incidents.assignee_id, incidents.technician_id

like image 107
AdminMyServer Avatar answered Jan 14 '23 17:01

AdminMyServer