使用枚举字段在Rails中进行单表继承的缺点是什么?

huangapple go评论56阅读模式
英文:

What are the cons of using enum field for single table inheritance in rails?

问题

I am refactoring an existing model using single table inheritance because the model logic has too many paths based on a column which is enum.

我正在重构一个现有的模型,因为该模型的逻辑基于一个枚举列,有太多不同的路径。

I want to pull out one type at a time keeping the other things as it is.

我想逐步提取一种类型,保持其他内容不变。

I used the existing column instead of adding new type column
example code

我使用了现有的列,而不是添加新的 type 列,示例代码:

class Experiment < ApplicationRecord
  self.inheritance_column = :experiment_type 

  enum experiment_type: {
    CampaignExperiment: 0,
    UserExperiment: 1,
  }
end

class CampaignExperiment < Experiment
end

This code works now and specs are passing.

这段代码目前可以工作,并且规范测试也通过了。

But rails docs suggests to use type column which is string.

但 Rails 文档建议使用字符串类型的 type 列。

What are the things I should take care if I am using enum? Will it backfire in the future because its enum?

如果我使用枚举,我应该注意哪些事情?它将来会因为是枚举而出现问题吗?

英文:

I am refactoring an existing model using single table inheritance because the model logic has too many paths based on a column which is enum.

I want to pull out one type at a time keeping the other things as it is.

I used the existing column instead of adding new type column
example code

class Experiment < ApplicationRecord
  self.inheritance_column = :experiment_type 

  enum experiment_type: {
    CampaignExperiment: 0,
    UserExperiment: 1,
  }
end

class CampaignExperiment < Experiment
end


This code works now and specs are passing.
But rails docs suggests to use type column which is string.
What are the things I should take care if I am using enum? Will it backfire in the future because its enum?

答案1

得分: 0

使用枚举在运行时失败,当实验控制器尝试通过传递实验类型属性来创建特定类型的实验时。

由于我想一次迁移一个experiment_type,仍然保持了当处理请求时通过控制器设置experiment_type的方式。

我不得不添加一个新的列type,并保持它与experiment_type同步,这样我就可以将实验类型单独提取到自己的子类中,而不会破坏其他任何内容。

英文:

Using enum fails in runtime when Experiment controller tries to create an specific type of experiment by passing experiment_type attribute.

Since I want to migrate one experiment_type at a time still keeping how experiment_type was set via controller when a request is processed.

I had to add a new column type and keep that in sync with experiment_type so I could pull out on experiment type to its own subclass without breaking anything else.

huangapple
  • 本文由 发表于 2023年4月13日 21:49:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定