[英]Rails: belongs_to vs has_one
A bit of a newbie question on rails associations. 关于Rails协会的一个新手问题。
I have a Bug model, and a Status model. 我有一个错误模型和一个状态模型。 Status is basically just a key/value pair table.
状态基本上只是一个键/值对表。 Out of the choices available, I would say Bug has_one Status makes the most sense.
在可用的选项中,我会说Bug has_one Status最有意义。 However, according to this
然而,根据本
Content belongs_to ContentTemplate.
内容归属于ContentTemplate。 Go back and look at how I described the problem, and you'll see that it works.
回头看看我如何描述该问题,您会发现它可行。 With belongs_to, the table accepts responsibility for the foreign key.
使用belongs_to,表对外键承担责任。 So Content has a content_template_id.
因此,内容具有content_template_id。 And ContentTemplate doesn't need anything.
而且ContentTemplate不需要任何东西。 I can point to it at will.
我可以随意指出。 Done.
做完了
Bug belongs_to Status would be more appropriate (since Bug should take the foreign key). Bug属具属于状态会更合适(因为Bug应该带外键)。 Semantically, his example makes sense, but mine makes none.
从语义上讲,他的榜样很有道理,但我的榜样却毫无意义。 Is this just a quirk of rails where in this situation it looks odd, or am I not understanding something/doing it wrong?
这只是在这种情况下看起来很奇怪的怪癖,还是我不明白某件事/做错了什么?
Yes, I think you've just found a slightly odd-looking scenario in Rails. 是的,我认为您刚刚在Rails中发现了一个看起来有些奇怪的场景。 I suppose it might be useful to view "status" as a sort of category to which the bug belongs — in that light, it makes sense.
我认为将“状态”视为该错误所属的类别可能是有用的-鉴于此,这是有道理的。
TABLE:
Bug
id integer
desc string
status_id integer fk
Status
id integer
desc string
RAILS MODEL:
Bug
belongs_to :status
Status
has_many :bugs
You didn't explain precisely what kind of relationship between Bug and Status you would like to get, but I assume you are interested in one of the following: 您没有确切说明您希望获得的Bug与Status之间的哪种关系,但我认为您对以下其中一项感兴趣:
has_many
in Bug class and belongs_to
in Status class, has_many
在Bug类和belongs_to
在状态类, has_one
in Bug class and belongs_to
in Status class. has_one
,Status类中应具有belongs_to
。 In both cases Status contains the foreign key. 在两种情况下,状态都包含外键。 In the second case the wording is a little odd, due to the fact that one-to-one relationship is in fact asymmetric (there should be a FK on one side only).
在第二种情况下,措辞有点奇怪,因为事实是一对一关系实际上是不对称的(仅一侧应有FK)。
If Status is just a look-up/key-value table, it sounds like you might want a habtm ( has_and_belongs_to_many
) relationship between Status and Bug. 如果Status只是一个查找/键值表,听起来您可能希望Status和Bug之间存在habtm (
has_and_belongs_to_many
)关系。 With habtm, what you'll end up with is a bugs_statuses
join table that has bug_id
and status_id
columns along with your bugs and statuses tables. 使用habtm,最终将得到一个
bugs_statuses
连接表,该表具有bug_id
和status_id
列以及您的bug和状态表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.