在 Rails 中将状态值建模为关联的正确方法是什么?
我有一个名为“联系人”的模型。
联系人可以有不同的状态“坏的、积极的、错误的......”
这些状态可能需要随着时间的推移而改变,但对于所有联系人来说,它们是相同的选项。
我应该这样建模:
Contacts.rb
belongs_to :status_contact
StatusContacts.rb
has_many :contacts
然后我手动填充表中的状态类型吗?
然后,我想使用 Ajax 单击与某个值对应的按钮来更新“联系人”的值。
I have a model called Contacts.
Contacts can have different status "bad, positive, wrong..."
These status may need to be changed over time, but across all contacts, they are the same options.
Should I model it this way:
Contacts.rb
belongs_to :status_contact
StatusContacts.rb
has_many :contacts
Then I manually populate the types of status in the table?
I then want to use Ajax to click a button corresponding to a value to update the value for Contacts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您正在尝试确保您的状态值始终仅限于您选择的一组可能的答案。如果这就是您想要做的全部事情,则没有特别需要单独的表。您可以在这里使用 ActiveRecord 验证的魔力。
首先,为联系人创建一个名为 :status 的字符串数据库列。
然后,您可以使用验证来确保这些值仅限于您想要的值。在 Rails 3 中,您可以这样做:(
如果您使用的是 Rails 2,请改用#validates_inclusion_of。)
在 ActiveRecord 中,验证会在保存之前检查对象的值是否有效;它拒绝将对象持久保存到数据库中,直到所有验证都通过。
It looks like you're trying to ensure that the values for your status are always going to restricted to a set of possible answers of your choosing. If that's all you're trying to do, there's no special need for a separate table. You can use the magic of ActiveRecord validations instead here.
First, create a string database column for Contact called :status.
Then you can use a validation to ensure that the values are limited to the ones you want. In Rails 3, you can do it like this:
(If you're using Rails 2, use #validates_inclusion_of instead.)
In ActiveRecord, validations check that the object's values are valid before saving; it refuses to persist the object into the database until all validations pass.
您的命名让我觉得有点奇怪 -
ContactStatus
对我来说听起来更好一点 - 但我认为这是实现您想要的目标的总体思路。Your naming strikes me as a little weird—
ContactStatus
sounds a little nicer to me—but I see this as being the general idea to achieve what you want.目前还没有明确的答案 --- 我认为我需要使用该表,因为它允许用户添加和修改在其应用程序中使用的状态类型。
No clear answer yet --- I think I need to use the table because it would allow the users to add and modify the types of status used across their application.