Multi-association using STI is not working

76 views Asked by At

I have Employee model and TicketStatus model using STI approach on Employee model in order to have to child models 'Advisor' and 'Staff', inside my TicketStatus i am trying to achieve the following: making a relation between TicketStatus and Advisor , TicketStatus and Staff, then TicketStatus and PreviousAdvisor , TicketStatus and PreviousStaff, my code is like this:

class TicketStatus < ActiveRecord::Base
  attr_accessible :status_id, :ticket_id , :staff_id, :advisor_id, :previous_advisor_id, :previous_staff_id
  belongs_to :status
  belongs_to :ticket
  belongs_to :staff, class_name: 'Staff', foreign_key: 'staff_id'
  belongs_to :previous_staff , class_name: 'Staff', foreign_key: 'previous_staff_id'
  belongs_to :advisor, class_name: 'Advisor', foreign_key: 'advisor_id'
  belongs_to :previous_advisor, class_name: 'Advisor', foreign_key: 'previous_advisor_id'
end

enter image description here

the problem is i cannot have two association on the same class name , after generating a dependency diagram using rubymine i found that the second association is overwriting the first association , what can i do in order to make those association works correctly ?

1

There are 1 answers

4
Niall Paterson On BEST ANSWER

This is happening because the foreign keys are the same. You can specify what the foreign keys should be for the second relationship in both cases like this:

belongs_to :previous_staff , class_name: 'Staff', foreign_key: 'previous_staff_id'

belongs_to :previous_advisor, class_name: 'Advisor', foreign_key: 'previous_advisor_id'

That'll preserve the separate relationships. The staff and the advisor relationships are fine.

EDIT: This was answered after the considerable edit of the question.