英文:
Paper trail object changes and rails enums
问题
我正在处理一个旧项目中模型的版本问题。项目中几乎所有的枚举值都是整数。在使用object_changes跟踪更改时,这些值显示为整数,这对查看数据的最终用户来说不够清晰。
例如
class Article
has_paper_trail
enum status: {draft: 0, published: 1}
end
记录保存时,对象更改为 status :[0,1]
有没有一种方法可以保存或显示状态键而不是值?
英文:
I'm working on versioning models in an old project. almost all of the enum's values used in the project are integers. when tracking changes with object_changes the values are displayed as integers, which is not clear to the end user viewing this data.
for example
class Article
has_paper_trail
enum status: {draft: 0, published: 1}
end
the record is saved with object changes status :[0,1]
is there a way either to save or display the status key instead of the value?
答案1
得分: 1
可以通过使用以下代码获得枚举值的可读形式。
version = Article.first.versions.last
version.changeset["status"]
为了更进一步,迁移您的数据并将枚举值定义为 'status',如下所示。
enum status: {draft: :draft, published: :published}
Rails 将值保存为字符串;因此,它的属性必须具有兼容的数据类型。
英文:
You can obtain the readable form of the enum value by using the following code.
version = Article.first.versions.last
version.changeset["status"]
To go even further, migrate your data and define your enums for 'status' as follows.
enum status: {draft: :draft, published: :published}
Rails will save the values as strings; therefore, its attribute must have a compatible data type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论