我应该在 ruby​​ on Rails 中使用 has_one 还是 Belongs_to ?

发布于 2024-09-08 13:07:18 字数 544 浏览 1 评论 0原文

我想要一个 Status 模型,在进行一些用户定义的设置后,该模型将相对静态(并且不同的用户可能有不同的状态值)。

状态可以应用于不同的模型,例如 ContactEvent

因此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甩你一脸翔 2024-09-15 13:07:18

有一个关于此的指南问题。您的情况略有不同,因为您的 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.

琉璃繁缕 2024-09-15 13:07:18

只是为了在更一般的设置中完成答案,这可以驱动您的选择:在具有外键的模型中使用 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.

窝囊感情。 2024-09-15 13:07:18

首先,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文