如何将状态保存为数据库中的代码,但将它们映射到 Rails 中有意义的单词?

发布于 2024-08-22 12:10:05 字数 171 浏览 3 评论 0原文

我需要一些帮助,请...

如果我将事务状态保存为数据库中的代码,但我想将它们转换为有意义的名称,我该怎么做?这还推荐吗?如果不是,有什么替代方案?

例如: 在数据库中,状态为“S”、“P”、“A” 在实际的应用程序中,我想相应地显示:“已提交”、“待处理”、“已批准”。

谢谢你!

I need some help with this, please ...

If I save a transaction status as a code in the db, but I want to translate them to meaningful names how do I do that? Is that even recommended? If no, what would be an alternative to that?

For example:
in the db the statuses are "S", "P", "A"
and in the actual application I'd like to display: "Submitted", "Pending", "Approved" accordingly.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痞味浪人 2024-08-29 12:10:05

举例来说,您有一个名为 Account 的模型,其中您将交易状态存储在名为 status 的列中,其值将是您提到的代码之一,您 通过这种方式,您可以

class Account < ActiveRecord::Base
  TRANSACTION_STATUS = {
    "S" => "Submitted",
    "P" => "Pending",
    "A" => "Approved"
  }

  def status
    TRANSACTION_STATUS[self[:status]]
  end
end

覆盖 Account 对象上的 activerecord 提供的方法 status

根据您将如何使用 status 字段,您可能需要在这些列上创建适当的索引(例如:如果您要选择具有待处理交易的帐户等)

Say for example you have a model called Account in which you are storing the transaction status in a column called status whose value will be ione of the codes that you have mentioned, you can do

class Account < ActiveRecord::Base
  TRANSACTION_STATUS = {
    "S" => "Submitted",
    "P" => "Pending",
    "A" => "Approved"
  }

  def status
    TRANSACTION_STATUS[self[:status]]
  end
end

By this way, your are overriding the method status provided by activerecord on Account object.

Depending on how you are going to use the status field, you might be required to create proper index on those columns (for ex: if you are going to select accounts with pending transaction, etc)

汐鸠 2024-08-29 12:10:05

您可以尝试使用 枚举列插件 来获取此功能。

迁移以创建表:

add_column :accounts, :status, :enum, :limit => [:submitted, :pending, :approved],
      :default => :submitted

在模型中:

validates_columns :status

在控制器中

@account = Account.new # It just works :)

You could try using the enum column plugin to get this functionality.

Migration to create the table:

add_column :accounts, :status, :enum, :limit => [:submitted, :pending, :approved],
      :default => :submitted

In the model:

validates_columns :status

In the controller

@account = Account.new # It just works :)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文