表示 ActiveRecord 关联中的多个 Null/Generic 对象?
我有一个属于医生的案例文件模型。除了所有“真正的”医生之外,还有几种通用医生:“自我治疗”、“未指定”和“移除”(曾经有真正的医生,但现在不再有)。我怀疑将来还会有更多的通用值。
我从数据库中从种子生成的特殊“医生”开始。通用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您可以在 Casefile 模型中添加一个额外的字段,例如,
treatment
(将设置为“自我治疗”、“未指定”等)您可以添加验证以确保 Casefile 指定了医生或治疗:
然后您可以使用治疗字段使用
.where
查找 Casefile:如果您愿意,您可以将治疗作为额外模型,其中 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:
Then you could use the treatment field to find Casefile's using
.where
:If you wanted, you could have treatment as an extra model, where Casefile
has_one
Doctor andhas_one
Treatment - but it seems like your needs are too simple to warrant that.