Two "has_one" relationships linking to the same table?


#1

How do i get two “has_one” relationships to the same table?

I have an audit table with fields auditor_id and manager_id that both
link to the people table:

AUDIT:
id
name
datecreated
auditor_id
manager_id

PEOPLE:
id
name

I have no idea how to link both fields from audit to people?? any
ideas??
I’m pulling my hair out trying to figure this out, please help!!

I know that if it were just one field then i’d call the field person_id.
What do i call a second field linking to the same table ???
person_id_2???
please help.

Thanks,
Chris


#2

Hi,

I think the trick is getting the has_many and belong_to in the correct
places. Since Audit references the People class, it is Audit that
belongs to
the People. I hope I got this right way around. I think this should work
(untested code).

Class Audit < ActiveRecord::Base

belongs_to :auditor,
:class_name => “People”,
:foreign_key => “auditor_id”

belongs_to :manager,
:class_name => “People”,
:foreign_key => “manager_id”

end

Class People < ActiveRecord::Base

has_many :auditor_audits,
:class_name => “Audit”,
:foreign_key => “auditor_id”

has_many :manager_audits,
:class_name => “Audit”,
:foreign_key => “manger_id”

end

belongs_to docs:
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000466

has_many documentation:
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000464

-Peter


#3

Chris H. wrote:

audits

auditor specific functionality

end

class Manager < Person
has_many :audits
#manager specific functionality
end

Not going to cut it. This logically implies that a person can be an
Auditor or a Manager but not both and identifes them in the Person
record (by the mandatory ‘type’ field for STI.

Why not just:

class Audit < ActiveRecord::Base
has_one :auditor, :foreign_key => ‘auditor_id’, :class_name =>
‘Person’
has_one :manager, :foreign_key => ‘manager_id’, :class_name =>
‘Person’
end


#4

You might want to look into single table inheritance…

example:

people

id
name
type

audits

id
auditor_id
manager_id

class Person < ActiveRecord::Base
end

class Auditor < Person
has_many :audits

auditor specific functionality

end

class Manager < Person
has_many :audits
#manager specific functionality
end

class Audit < ActiveRecord
belongs_to :auditor
belongs_to :manager
end

bob = Manager.create(:name => “Bob”)
joe = Auditor.create(:name => “Joe”)
Audit.create(:manager_id => bob.id http://bob.id, :auditor_id =>
joe.idhttp://joe.id
)

audit = Audit.find(1)
puts audit.manager # ==> bob
puts audit.auditor # ==> joe

puts bob.audits
puts joe.audits