繁体   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