2009-12-22 25 views
2

我正在創建一個具有三種模型的Rails應用程序。一個模型代表汽車,另一個模型代表可以塗上汽車的顏色,而第三個模型代表某種顏色的汽車訂單。構建這些模型之間關係的最佳方式是什麼?在Rails中建模這些關係的最佳方法

回答

3

這是非常基本的東西。我建議你仔細閱讀關於Active Record關聯的Rails guide。爲了讓你去:

class Car < ActiveRecord::Base 
    has_many :orders 
    belongs_to :color 
end 

class Color < ActiveRecord::Base 
    has_many :cars 
    has_many :orders 
end 

class Order < ActiveRecord::Base 
    belongs_to :car 
    belongs_to :color 
end 
+0

不是一個糟糕的開始,可能需要添加驗證到訂單,以確保訂單中的顏色與選定的汽車兼容。 – EmFi

0

我覺得這與Janteh有點不同。當您下訂單時,您以特定顏色訂購特定汽車,對吧?所以,我認爲汽車和顏色應通過順序有關,是這樣的:

class Car < ActiveRecord::Base 
    has_many :orders 
end 

class Color < ActiveRecord::Base 
    has_many :orders 
end 

class Order < ActiveRecord::Base 
    belongs_to :car 
    belongs_to :color 
end 

這主要是什麼Janteh建議,但我沒有車直接與特定顏色相關聯。

+0

但是你也想知道你可以訂購某款車的顏色是多少? – Janteh

0

我更喜歡has_many:通過關係。這樣,您可以訪問訂購了某輛汽車的所有顏色,並且所有汽車都以特定顏色訂購。

class Car < ActiveRecord::Base 
    has_many :orders 
    has_many :colors, :through => :orders 
end 

class Color < ActiveRecord::Base 
    has_many :orders 
    has_many :cars, :through => :orders 
end 

class Order < ActiveRecord::Base 
    belongs_to :car 
    belongs_to :color 
end 
相關問題