我应该在自己专用的 table 中提供我的允许字段值列表吗?

Should I provide my list of allowed field values in their own dedicated table?

我有一个模型 'Person' 表示一个数据库 table 'people':

class Person < ApplicationRecord
  validates :age, numericality: { only_integer: true }
end

def change
  create_table :people do |t|
    t.string :first_name
    t.string :second_name
    t.integer :age
    t.string :phone_number
    t.text :description
    t.timestamps
  end
end

我想添加一个名为 'star_sign' 的附加字段,它只能包含十二星座(摩羯座、狮子座、天蝎座等)之一的名称。

我的correct/best实践方法是什么?

1) 创建一个单独的 table、star_sign,包含十二星座中每一个的记录,并与模型 'Person' 建立 belongs_to 关系'StarSign' 和从 'StarSign' 到 'Person'?

的 has_many 关系

2) 在模型 'Person' 的 class 定义中编写一些验证代码,这将强制我在 'people' table 中的 'star_sign' 字段只接受与十二生肖名称完全匹配的十二个字符串之一?

如果是 2,有人可以给我合适的代码吗?或者即使 1 是最佳解决方案,我仍然有兴趣查看用于实现 2 的代码。

看来最好的解决办法是使用 ActiveRecord::Enum class 提供的功能。

我将此代码添加到我的 'Person' 模型中:

enum star_sign: [ :leo, :capricorn, :aries, :libra, :scorpio, :taurus, :virgo, :cancer, :gemini, :aquarius, :sagittarius, :pisces ]

然后我将此字段添加到我的 'people' table:

t.integer :star_sign

使用enum时需要声明该字段为整数类型,因为我们让系统知道要存储哪个生肖的方式是通过其对应的元素索引号。例如,"leo" 为 0,"pisces" 为 11。