Paper trail对象更改和Rails枚举

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

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.

huangapple
  • 本文由 发表于 2023年3月12日 16:50:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711990.html
匿名

发表评论

匿名网友

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

确定