单表继承以及在 Rails 中的使用位置 [英] Single table inheritance and where to use it in Rails

查看:30
本文介绍了单表继承以及在 Rails 中的使用位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了一个奇怪的设计问题,

I am stuck in a weird Design problem,

我正在研究两种类型的配置文件模型,

I am working on a two type of profiles Models,

  • 用户个人资料(属于用户)
  • 在站点内作为机器人"维护的其他人(不属于任何人)

这两种配置文件的典型 OO 行为是相同的,但只有重要的属性/属性是通用的(非常重要的 5-6 个),其他属性如兴趣等"(几乎 10-15 个属性)不存在机器人配置文件

The typical OO behaviour of these two types of Profiles is same but only the important attributes/properties are common ( the very important ones 5-6 in number), others properties like "interests etc"(almost 10-15 properties) are not there for bot profiles

早先从事此工作的编码员为机器人配置文件/用户配置文件创建了单独的模型/控制器,这在各处创建了大量冗余,并且正如预期的那样难以维护,编写测试等.我想把它弄干,至少要解决部分/所有这些冗余问题.

The coder who worked on this earlier created separate models/Controllers for bot profiles / User profiles which creates a lot of redundancy everywhere and also as expected hard to maintain, write tests etc.I wanted to DRY this up, atleast to solve some/all of these redundancy problems.

有人建议使用单表继承作为解决方案

Somebody suggested Single Table Inheritance as a solution

有人建议改用多态关联.

Somebody suggested Use Polymorphic Associations instead.

什么是更好的方法.我们什么时候真正使用 STI?

what is the better approach. When do we actually use STI?

我自己的想法是,当模型的属性相同且行为不同时,最好使用 STI.

My own thought was STI is used best when attributes are same for Models and they differ in behaviour.

想想我能做什么?

推荐答案

当属性相同但行为不同时,将 STI 表征为最有用是大致正确的",但可能有点限制.顾名思义,当存在明确的OO风格的继承关系,而不是不同类型的对象之间的数据库风格的关系时,我喜欢使用STI.

Characterising STI as mostly useful when attributes are the same but behaviour differs is "about right", but possibly a little limiting. I like to use STI when there is, as the name suggests, a clear OO-style inheritance relationship, rather than the database-style relationship between objects of different types.

如果机器人和用户之间有共同的代码,我会说 STI 听起来像是赢家.如果只是一些共同的属性,它可能不太适用,但仍然值得一试.

If there is common code between bots and users, I'd say STI sounds like a winner. If there's just some common attributes, it's probably less applicable but still worth having a go at.

我是一个很有实验性的人,所以我的建议是试一试.分支代码并将模型重构为 STI 关系.看看它是否真的让事情变得枯燥乏味,或者只是将一组头痛换成了其他一些问题.

I'm a pretty experimental person, so my recommendation is to give it a go. Branch your code and refactor the models into an STI relationship. See if it really does dry things up, or just swaps one set of headaches for some other problem.

我认为您不会从中受益的一件事是让您的控制器枯竭.根据我的经验,STI 模型通常不会转化为类似的相关控制器.但这将是另一回事.有时胜利,有时没有.

One thing I think you won't see much benefit from is drying up your controllers. In my experience, STI models don't often translate into similarly related controllers. But that would be something else to experiment with. Sometimes there's a win, sometimes there isn't.

这篇关于单表继承以及在 Rails 中的使用位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆