首页 > 解决方案 > 在 Rails 中将模型常量实现为列表或枚举

问题描述

我有一个模型常数,它基本上是environments如下值:

class Account
  has_many :account_configs
  accepts_nested_attributes_for :account_configs
  ACCOUNT_ENVS = %w[development staging production].freeze
end

class AccountConfig
  validates :account, presence: true
  validates :environment, inclusion: {in: Account::ACCOUNT_ENVS}
end

该常数ACCOUNT_ENVS也用于view. 现在这对我的情况很有效,但我应该在这里使用enum吗?如果是,我该如何使用它?

标签: ruby-on-railsrubyruby-on-rails-5

解决方案


您可以进行以下迁移,

class ChangeEnvironmentOfAccountConfig < ActiveRecord::Migration
  def up
    change_column :account_configs, :environment, :integer, default: 0
  end
end

默认值始终设置为development

在模型中,

class AccountConfig
  enum environment: %w(:development, :staging, :production)
end

config = AccountConfig.create

config.environment
# => "development"

config.production?
# => false

config.production! #updates the object

AccountConfig.development # acts as scope to filter with environment 

推荐阅读