2017-11-20 11 views
0

Ich bin neu beim Lernen von Rails und ich bin etwas verwirrt über Assoziationen.Rails `has_many` association

Sagen Sie zum Beispiel, habe ich ein Car, die gehören, können entweder ein Owner, ein Renter oder ein Company und kann nur auf ein von ihnen gehören und Owner, Renter oder Company können viele Cars haben.

Wie empfehlen Sie, dass ich dieses Szenario modelliere? Sollte es drei Fremdschlüssel auf der Car Tabelle für owner_id, render_id und company_id geben? Oder haben Sie eine Art Join-Tabelle für jede von ihnen, die in etwa so aussehen würde:

 
| car_id | owner_id | 
|--------|----------| 
| 1  | 1  | 
| 2  | 1  | 
| 3  | 1  | 

Oder gibt es eine andere Möglichkeit, dies zu erreichen? Unter Berücksichtigung, dass mehr Abhängige (mehr Gruppen von Mietern, Eigentümern etc.) hinzugefügt werden könnten.

Vielen Dank im Voraus.

Antwort

3

Dies ist ein klassisches Beispiel dafür, wo Sie eine polymorphe Vereinigung verwenden würde.

class Car 
    belongs_to :possessor, polymorphic: true 
end 


class Owner 
    has_many :cars, as: :possessor 
end 

class Renter 
    has_many :cars, as: :possessor 
end 

class Company 
    has_many :cars, as: :possessor 
end 

Es gibt zwei neue Felder in der cars Tabelle, possessor_type und possessor_id und Sie können sie mit Migrations hinzufügen, und Sie können auch andere Modelle hinzufügen, die ein Auto besitzen könnte und es gibt keine Notwendigkeit mehr Spalten zu cars hinzufügen

0

Eine mögliche Wege: make Car haben Fremdschlüssel auf Owner, Renter, Company.

Hier ist ein Beispiel.

class Car < ApplicationRecord 
    belongs_to :owner 
    belongs_to :renter 
    belongs_to :company 
end 

class Owner < ApplicationRecord 
    has_many :cars 
end 

class Renter < ApplicationRecord 
    has_many :cars 
end 

class Company < ApplicationRecord 
    has_many :cars 
end 
 
Cars table 
id| owner_id | renter_id | company_id | 
- |----------|-----------|------------| 
1 | 1  | 1   |2   | 
2 | 1  | 1   |1   | 
3 | 3  | 2   |1   | 

The has_many Association