我已阅读关于关联的指南,但我觉得我还没有完全理解,所以我想问几个问题以确保。比方说,我正在制作一个应用程序,其中包括列出世界各地的大城市。我打算制定一个从大陆级开始并可以过滤的视图。所以我会从一个大陆模型开始。然后是一个国家模式。现在,在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