[英]Should I use has_one or belongs_to in ruby on rails?
I want to have a Status
model 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 Contact
and Event
. 状态可以应用于不同的模型,例如Contact
和Event
。
so the statuses returned by contact.status
will be different from event.status
所以contact.status
返回的状态与event.status
不同
I want to design the app so that status table has different types ( contacts
and events
). 我想设计应用程序,以便状态表具有不同的类型( contacts
和events
)。
What is the right strategy and format for this? 什么是正确的策略和格式?
I am thinking of declaring :has_one Status
in the Contact
model, and storing a :status_id
in the :contacts
table. 我想在Contact
模型中声明:has_one Status
,并在:contacts
表中存储:status_id
。 Ditto with Event
. 与Event
同上。
:statuses
table will have the status value, type, and date. :statuses
表将具有状态值,类型和日期。
does this make sense? 这有意义吗? Can you suggest a better approach? 你能建议一个更好的方法吗?
There is a guide on this very 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'. 你的情况略有不同,因为好像你的状态模型真的需要是多态的,因为不同的东西将是“可以状态的”。
To answer your question, Contact/Event has_one Status does make sense to me. 要回答您的问题,请联系/事件has_one状态对我有意义。
只是为了在更一般的设置中完成答案,可以推动您的选择: belongs_to
关联在具有外键的模型中使用。
Firstly, the has_one relationship does not store an id in the current model. 首先,has_one关系不在当前模型中存储id。 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. 要在联系人或事件中存储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? 其次,根据您在Status中存储的信息类型,为什么它需要是自己独立的表? Why not make a status column in each model you want to use status on? 为什么不在每个要使用状态的模型中创建状态列? A little more information may be useful here. 这里可能会提供更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.