2017-11-20 11 views
0

私はRailsを初めて学びました。私は関連について少し混乱しています。Rails `has_many` association

例えば、私はOwnerRenterまたはCompanyのいずれかに属することができますし、それらだけのに属することができますし、OwnerRenterまたはCompanyが多くCarsを持つことができます。Carを持っていると言います

私はこのシナリオのモデリングについてどうお勧めしますか? owner_idCarテーブルに3つの外部キーがある場合、render_idcompany_idはありますか?あるいは、それぞれのための何らかの並べ替えテーブルを用意してください。

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

これを達成する別の方法はありますか?より多くの扶養家族(賃貸人、所有者のより多くのグループ)が追加されることを考慮しながら。

ありがとうございます。

答えて

3

これはポリモーフィックな関連を使用する場所の典型的な例です。

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 

の2つのがあり、新たなcarsテーブルのフィールド、possessor_typepossessor_idがあり、あなたが移行してそれらを追加することができ、あなたが車を持っているかもしれない他のモデルを追加することができますし、carsに複数の列を追加する必要はありません

0

可能な方法の1つ:OwnerRenterCompanyに外部キーを持つようにCarを設定します。

ここは例です。

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