2013-10-03 116 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