我应该在 ruby on rails 中使用has_one 还是belongs_to?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3217067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I use has_one or belongs_to in ruby on rails?
提问by Timothy T.
I want to have a Statusmodel which will be relatively static after some user-defined set up (and different users may have different values on status).
我想要一个Status在一些用户定义的设置后相对静态的模型(不同的用户可能有不同的状态值)。
The status can apply to different models, such as Contactand Event.
状态可以应用于不同的模型,例如Contact和Event。
so the statuses returned by contact.statuswill be different from event.status
所以返回的状态contact.status将不同于event.status
I want to design the app so that status table has different types (contactsand events).
我想设计应用程序,以便状态表具有不同的类型(contacts和events)。
What is the right strategy and format for this?
什么是正确的策略和格式?
I am thinking of declaring :has_one Statusin the Contactmodel,
and storing a :status_idin the :contactstable. Ditto with Event.
我正在考虑:has_one Status在Contact模型中声明,并将 a 存储:status_id在:contacts表中。同上Event。
:statusestable will have the status value, type, and date.
:statuses表将具有状态值、类型和日期。
does this make sense? Can you suggest a better approach?
这有意义吗?你能提出更好的方法吗?
回答by theIV
There is a guide on thisvery question. Your situation is slightly different in that it seems as though your Status model really needs to be polymorphic since different things will be 'statusable'.
有一个关于这个问题的指南。您的情况略有不同,因为似乎您的 Status 模型确实需要多态,因为不同的东西将是“可状态的”。
To answer your question, Contact/Event has_one Status does make sense to me.
要回答您的问题,联系/事件 has_one 状态对我来说确实有意义。
回答by epsilones
Just to complete the answer in a more general setting, that can drive your choice : belongs_toassociation is used in the model that has the foreign key.
只是为了在更一般的设置中完成答案,这可以驱动您的选择:belongs_to在具有外键的模型中使用关联。
回答by nuclearsandwich
Firstly, the has_one relationship does not store an id in the current model. It looks for a foreign key in the relative table. In order to store a status_id in Contacts or Events you'd use belongs_to.
首先, has_one 关系不会在当前模型中存储 id。它在相关表中查找外键。为了在联系人或事件中存储 status_id,您可以使用belongs_to。
Secondly, depending on the type of information you're storing in Status, why does it need to be its own separate table? Why not make a status column in each model you want to use status on? A little more information may be useful here.
其次,根据您在 Status 中存储的信息类型,为什么它需要是自己的单独表?为什么不在要使用状态的每个模型中创建一个状态列?多一点信息可能在这里有用。

