2013-10-03 117 views
0

我已閱讀關於關聯的指南,但我覺得我還沒有完全理解,所以我想問幾個問題以確保。比方說,我正在製作一個應用程序,其中包括列出世界各地的大城市。我打算制定一個從大陸級開始並可以過濾的視圖。所以我會從一個大陸模型開始。然後是一個國家模式。現在,在Continent模型中,我將把關聯定義爲has_many:countries。而在國家模式中,我會使用belongs_to:continents。我掌握的很多。所以我的下一個模型將成爲州/省的模型。讓我們把它稱爲省,因爲這在全世界是比較常見的。所以現在我有我的省模型,我會使用belongs_to:country。同樣,各國也會有一些省份。我的第一個問題是,我如何描述省與大陸之間的關係? Has_many通過描述兩個模型都有很多的關聯。一個省只有一個大陸。 Has_one通過第三個對象描述具有一對一關係的對象之間的關係。同樣,情況並非如此,因爲歐洲大陸會有很多省份。所以這是我的主要問題。如何通過上下文描述一對多關係。我的第二個問題只是在稍後添加另一個圖層(比如County)的情況下,要求提供有關爲此編寫遷移的提示。但主要問題只是瞭解如何表達我描述的關係。或者如果他們甚至需要表達。 ETA:如果我要使用has_many_through關聯,是否需要創建連接表(continent_province),或者我可以簡單地使用國家表,即has_many:provinces - > through:countries?RoR的has_many/belongs_to關聯

+0

很大程度上取決於您希望如何使用數據。除非您需要直接連接,否則無需在Continent和Province之間定義直接鏈接。在這種情況下,是的,你可以做一個'has_many_through'。它將把許多省份與每個大洲聯繫起來。 – lurker

+0

感謝您的回覆。我擔心has_many_through關聯有兩個原因。首先,它被定義爲多對多,不多對一。其次,如果我要使用has_many_through,是否需要創建一個連接表並將連接表用作「through」表?使用「國家」作爲「貫穿」表似乎更有意義,但那不是國家表的目的。或者我只是在想這個?這是已知的事情發生。 –

+0

您是否閱讀過http://guides.rubyonrails.org/association_basics.html? – lurker

回答

1

不要因爲某些文檔某處的一些小例子而太忙。關係支持非常靈活。最後,請試一試 - 我有一個Tester應用程序,它有各種概念驗證 - 這就是它的目的。


class Project 
    # one-to-many 
    has_many :scenarios 
    # linking through scenarios 
    has_many :unittests, :through => :scenarios 
    # polymorphic relationship, everything can be relation to one or more appls 
    has_many :appllinks, :as => :applinkable, :dependent => :destroy 
    has_many :appls, :through => :appllinks, :order => 'name' 
    blah blah blah 
end 

class Scenario 
    # many-to-one 
    belongs_to :project 
    # many-to-many 
    has_many :scenariotests 
    has_many :unittests, :through => :scenariotests 
    # polymorphic relationship, everything can be relation to one or more appls 
    has_many :appllinks, :as => :applinkable, :dependent => :destroy 
    has_many :appls, :through => :appllinks, :order => 'name' 
    blah blah blah 
end 

class Unittest 
    # many-to-many 
    has_many :scenariotests 
    has_many :scenarios, :through => :scenariotests 
    # polymorphic relationship, everything can be relation to one or more appls 
    has_many :appllinks, :as => :applinkable, :dependent => :destroy 
    has_many :appls, :through => :appllinks, :order => 'name' 
    blah blah blah 
end