我应该在 ruby on Rails 中使用 has_one 还是 Belongs_to ?
我想要一个 Status
模型,在进行一些用户定义的设置后,该模型将相对静态(并且不同的用户可能有不同的状态值)。
状态可以应用于不同的模型,例如 Contact
和 Event
。
因此 contact.status
返回的状态将与 event.status
不同
我想设计应用程序,以便状态表具有不同的类型(contacts
> 和事件
)。
正确的策略和形式是什么?
我正在考虑在 Contact
模型中声明 :has_one Status
, 并将 :status_id
存储在 :contacts
表中。 事件
也是如此。
:statuses
表将包含状态值、类型和日期。
这有道理吗?你能建议一个更好的方法吗?
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).
The status can apply to different models, such as Contact
and Event
.
so the statuses returned by contact.status
will be different from event.status
I want to design the app so that status table has different types (contacts
and 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. Ditto with Event
.
:statuses
table will have the status value, type, and date.
does this make sense? Can you suggest a better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个关于此的指南问题。您的情况略有不同,因为您的 Status 模型似乎确实需要多态,因为不同的事物将是“可状态”的。
为了回答您的问题,联系人/事件 has_one 状态对我来说确实有意义。
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.
只是为了在更一般的设置中完成答案,这可以驱动您的选择:在具有外键的模型中使用
belongs_to
关联。Just to complete the answer in a more general setting, that can drive your choice :
belongs_to
association is used in the model that has the foreign key.首先,has_one 关系在当前模型中不存储 id。它在相关表中查找外键。为了在联系人或事件中存储 status_id,您可以使用belongs_to。
其次,根据您在 Status 中存储的信息类型,为什么它需要有自己的单独表?为什么不在您想要使用状态的每个模型中创建一个状态列?此处提供更多信息可能会有用。
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.
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.