[英]Creating relationships in rails 4 (one model can belong to multiple other models)
I am trying to model links and nodes in Rails 4. A link can have two nodes (a source node and a target node). 我正在尝试在Rails 4中对链接和节点进行建模。链接可以具有两个节点(源节点和目标节点)。 A node can belong to multiple links.
一个节点可以属于多个链接。 I wrote this in my links model.
我在链接模型中编写了此代码。
class Links < ActiveRecord::Base
has_one :source_node, class_name: 'Node'
has_one :target_node, class_name: 'Node'
end
I wrote this for my node class. 我是为节点类编写的。 Is this correct?
这个对吗?
class Nodes < ActiveRecord::Base
belongs_to :link
end
Use cases for links: 链接的用例:
SN - L - TN
SN - L
L - TN
L
One link has one source node. 一个链接具有一个源节点。
One link has one target node. 一个链接具有一个目标节点。
Use cases for nodes: 节点用例:
L3
|
L1 - SN - L2
|
L4
One node has many links. 一个节点有许多链接。
So: 所以:
class Links < ActiveRecord::Base
belongs_to :source_node, class_name: 'Node' // didn't use has_one*
belongs_to :target_node, class_name: 'Node'
end
class Nodes < ActiveRecord::Base
has_many :links
end
The reason to use belongs_to instead of has_one is because Link would have the foreign key to Node. 之所以使用belongs_to而不是has_one是因为Link将具有Node的外键。
What if the relationship was defined in the opposite way? 如果关系以相反的方式定义怎么办? One where Node has the foreign key (belongs_to), and Link (has_one) of each type of node.
其中Node具有外键(belongs_to)和Link(has_one)每种类型的节点。 With that design you would need to define a field
link_N_id
for N links in the Node model. 通过这种设计,您将需要为Node模型中的N个链接定义一个字段
link_N_id
。
The problems are: 问题是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.