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

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

问题描述

我遇到了一个奇怪的设计问题,

I am stuck in a weird Design problem,

我正在处理两种类型的模型,

I am working on a two type of profiles Models,


  • 用户个人资料(属于用户)

  • 其他在网站内维护为bots的人(不属于任何人)

这两种类型的配置文件的典型OO行为是相同的,但只有重要的属性/属性是常见的(非常重要的属性/属性5-6 in数字),其他属性,如兴趣等(几乎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

之前参与此工作的编码人员创建了单独的模型/控制器对于bot配置文件/用户配置文件,它在各处创建了大量冗余,并且预期难以维护,编写测试等。我想干这个,至少解决部分/全部冗余问题。

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.

关于我该怎么做的想法?

Thoughts about what can I do?

推荐答案

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

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天全站免登陆