Rails 5 - Object Relation Impedence and how to structure multiple inherited classes/tables

后端 未结 3 1817
Happy的楠姐
Happy的楠姐 2021-01-18 12:42

EDIT I have edited this from the original to make it easier to understand.


I understand the Object Relationship Impedance problem. I understan

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 13:10

    I found a solution to my first Question. Leaving the models setup as they are in the question, I change the database to see if it would work.

    I changed the Assignment table so that the foreign_key is now called 'employee_id' since Rails seemed to want to insist on that.

    Then I changed the constraint, which now reads:

    ALTER TABLE public.assignments
      ADD CONSTRAINT fk_rails_52f37556f9 FOREIGN KEY (employee_id)
          REFERENCES public.people (id) MATCH SIMPLE
          ON UPDATE NO ACTION ON DELETE NO ACTION;
    

    Then the code works - but of course I would now have to write a migration script to create such a constraint.

    The original migration does not work, as it creates 'person_id':

      t.references :person, foreign_key: true
    

    This answer made it clear that Rails does not properly support foreign keys. SIGH

    The other problem with this solution is that if other subtypes of Person at some point in the future need to also be assigned to Projects, they can't be. So not a great solution really. Better to leave assignments related directly to Person.

提交回复
热议问题