DB with multiple foreign keys linked to same Model on differents attributes
2
Not solved Solved
3 months ago

Hello guys,

I am having difficulties building my DB relation, if anyone could give me a little help i would greatly appreciate!

I have one table named Person and another one called Company and Company has many Persons and Person belongs_to Company

Here the trick Company has many Person threw an attribute called person (belonging to Company) and has many Person threw another attribute called administrator (belonging to Company) basically its referring to a physical person and an adminstrator of a company.

Could be see like

Coca-cola = Company.new
jonathan = Person.new / nicolas = Person.new
Coca-cola : { 
person: jonathan,nicolas
administrator: nicolas
}

I did that first migration for adding targetted foreign key based on the name of my company attribute administrator and person :

def change
 add_reference :persons, :person, index: true
 add_reference :persons, :administrator, index: true

 add_foreign_key :persons, :companys, column: :person_id
 add_foreign_key :persons, :companys, column: :administrator_id
end

then I added this relation to my model

class Company < ApplicationRecord
  has_many      :persons,
  :class_name => "Person",
  :foreign_key  => "person_id"

  has_many      :administrators,
  :class_name => "Person",
  :foreign_key  => "administrator_id"
end

and

class Person < ApplicationRecord
  belongs_to    :person,
  :class_name => "Company",
  optional: true

  belongs_to    :administrator,
  :class_name => "Company",
  optional: true
end

And unfortunately that doesnt working, any lead on what could cause the problem ?

Thanks a lots.

Jonathan.

3 months ago

Hi,

If an administrator is a person, just had an admin boolean in your Persons table, and you will be able to select the admin person with an active record request . If you want an active record association have a look of polymorphic relationship : http://guides.rubyonrails.org/association_basics.html#polymorphic-associations.

Cheers Antoine

Cancel
Submit your answer