簡體   English   中英

RoR中的has_many / belongs_to關聯

[英]has_many / belongs_to associations in RoR

我已經閱讀了有關關聯的指南,但是我覺得我仍然還不完全了解,所以我想問幾個問題。 假設我正在制作一個應用程序,該應用程序除其他外將列出世界各地的大城市。 我將計划從大陸級別開始並可以向下過濾視圖。 所以我將從大陸模型開始。 然后是一個國家模型。 現在,在Continent模型中,我將關聯定義為has_many:countries。 在國家(地區)模型中,我將使用belongs_to:continents。 我掌握了這么多。 因此,我的下一個模型將是州/省的模型。 我們稱其為“省”,因為這在世界各地更為普遍。 所以現在我有了我的省模型,並且我將使用belongs_to:country。 同樣,國家也會有has_many:provinces。 我的第一個問題是,如何描述省與大陸之間的關聯? Has_many通過描述兩個模型都有很多的關聯。 一個省只有一個大陸。 Has_one到描述通過第三對象具有一對一關系的對象之間的關系。 同樣,情況並非如此,因為一個大陸將有許多省。 所以這是我的主要問題..如何通過上下文描述一對多存在的關系。 我的第二個問題是,在稍后添加另一層(例如County)的情況下,僅要求提供有關為此編寫遷移的提示。 但是主要的問題是僅僅了解如何表達我描述的關系。 或者甚至需要表達它們。

ETA:如果我要使用has_many_through關聯,是否必須創建一個聯接表(continent_province),還是可以簡單地使用國家表,即has_many:provinces->通過:countries?

不要在某個文檔中的幾個小示例上太費勁。 關系支持非常靈活。 最后,只需嘗試一下-我有一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM