英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论