表示 ActiveRecord 关联中的多个 Null/Generic 对象?

发布于 2024-12-17 04:04:35 字数 519 浏览 3 评论 0原文

我有一个属于医生的案例文件模型。除了所有“真正的”医生之外,还有几种通用医生:“自我治疗”、“未指定”和“移除”(曾经有真正的医生,但现在不再有)。我怀疑将来还会有更多的通用值。

我从数据库中从种子生成的特殊“医生”开始。通用Doctors只需要响应name、title、company、published?方法。

这对一个人来说很有效,对两个人来说就很紧张,现在感觉完全崩溃了。我想改变这种行为,但不知道如何测试它,这是一个坏兆头。创建用于测试的所有通用对象也很麻烦,包括通过所需 Doctor 属性的验证的假值。

空对象模式非常适合一个通用对象。 “name”方法可以返回“自我处理”,如 克雷格·安布罗斯

当存在多个状态非常有限的通用对象时,我应该使用什么模式?

I have a Casefile model that belongs_to a Doctor. In additional to all the "real" doctors, there are several generic Doctors: "self-treated", "not specified", and "removed" (it used to have a real doctor, but no longer does). I suspect there will be even more generic values in the future.

I started with special "doctors" in the database, generated from seed. The generic Doctors only need to respond to the name, title, company, published? methods.

This worked with one, was strained with two, and now feels completely broken. I want to change the behavior and can't figure out how to test it, a bad sign. Creating all the generic objects for testing is also trouble, including fake values to pass validation of the required Doctor attributes.

The Null Object pattern works well for one generic object. The "name" method could return "self-treated", as demonstrated by Craig Ambrose.

What pattern should I use when there are multiple generic objects with very limited state?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

夏夜暖风 2024-12-24 04:04:35

在我看来,您可以在 Casefile 模型中添加一个额外的字段,例如,treatment(将设置为“自我治疗”、“未指定”等)

您可以添加验证以确保 Casefile 指定了医生或治疗:

validate :has_doctor_or_treatment, :on => :save

def has_doctor_or_treatment
  (self.doctor.exists? || !treatment.blank?)
end

然后您可以使用治疗字段使用 .where 查找 Casefile:

Casefile.where(:treatment => "self-treated")

如果您愿意,您可以将治疗作为额外模型,其中 Casefile has_one 医生和has_one 治疗 - 但似乎您的需求太简单了,无法保证这一点。

It seems to me like you could just add an extra field to the Casefile model called, say, treatment (which would be set to "self-treated", "not specified" etc.)

You could add a validation to ensure a Casefile either has a doctor or treatment assigned:

validate :has_doctor_or_treatment, :on => :save

def has_doctor_or_treatment
  (self.doctor.exists? || !treatment.blank?)
end

Then you could use the treatment field to find Casefile's using .where:

Casefile.where(:treatment => "self-treated")

If you wanted, you could have treatment as an extra model, where Casefile has_one Doctor and has_one Treatment - but it seems like your needs are too simple to warrant that.

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