我已閱讀關於關聯的指南,但我覺得我還沒有完全理解,所以我想問幾個問題以確保。比方說,我正在製作一個應用程序,其中包括列出世界各地的大城市。我打算制定一個從大陸級開始並可以過濾的視圖。所以我會從一個大陸模型開始。然後是一個國家模式。現在,在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
A
回答
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
相關問題
- 1. ROR模型關聯問題
- 2. Ror創建表關聯
- 3. has_many/belongs_to RoR中的唯一關聯
- 4. 多關聯Hidden_Field編輯問題。 ROR
- 5. ROR按關聯查詢訂單
- 6. RoR用戶聯繫員工關係
- 7. 關於RoR數據庫模式和關聯的建議
- 8. ROR關係
- 9. RoR中的has_many關聯中的附加字段
- 10. RoR中模型的特定關聯的數量
- 11. RoR:破壞與has_many,:通過孤立的關聯
- 12. 獲取RoR 3中關聯的所有記錄
- 13. ActiveRecord RoR - 僅保存新的關聯對象
- 14. RoR:查找對象數組的所有關聯對象
- 15. ROR:檢查多態關聯中包含的對象
- 16. 數據庫新聞 - > RoR上的用戶關聯
- 17. RoR - 模型關係
- 18. 顯示RoR的關係
- 19. RoR上的關閉語句
- 20. 如果沒有關聯,RoR允許刪除
- 21. RoR活動記錄關聯查詢條件
- 22. RoR基於多對多關聯進行搜索,如標籤
- 23. RoR:通過has_and_belongs_to_many關聯兩個現有模型
- 24. ROR中的內聯附件2.3.8
- 25. 關聯關聯表
- 26. ROR多對多關係
- 27. RoR - 通過關聯創建的外鍵和遷移或「手動」(或腳手架)?
- 28. 如何關聯複選框用於更新RoR表中的字段?
- 29. 有關部署Ror的提示
- 30. 關於ActionMailer RoR的基本困惑
很大程度上取決於您希望如何使用數據。除非您需要直接連接,否則無需在Continent和Province之間定義直接鏈接。在這種情況下,是的,你可以做一個'has_many_through'。它將把許多省份與每個大洲聯繫起來。 – lurker
感謝您的回覆。我擔心has_many_through關聯有兩個原因。首先,它被定義爲多對多,不多對一。其次,如果我要使用has_many_through,是否需要創建一個連接表並將連接表用作「through」表?使用「國家」作爲「貫穿」表似乎更有意義,但那不是國家表的目的。或者我只是在想這個?這是已知的事情發生。 –
您是否閱讀過http://guides.rubyonrails.org/association_basics.html? – lurker