gpt4 book ai didi

ruby-on-rails - 如何创建枚举类型并默认为新对象的特定值

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:00 25 4
gpt4 key购买 nike

我有一个模型

class Transaction < ActiveRecord::Base

end

我有一个 transaction_type 列,它是一个整数。

我怎样才能创建一个可以将值映射到名称的枚举,例如:

one_time = 1
monthly = 2
annually = 3

因此在 db 列中,值将是 1、2 或 3。

此外,每当我创建一个新实例或保存一个模型时,字段设置如下:

@transaction = Transaction.new(params)

它应该默认为 1(on_time)。

我不确定我该怎么做?

最佳答案

基本上与阿米特的答案相同,略有不同

class TransactionType
TYPES = {
:one_time => 1,
:monthly => 2,
:annually => 3
}

# use to bind to select helpers in UI as needed
def self.options
TYPES.map { |item| [item[0], item[1].to_s.titleize] }
end

def self.default
TYPES[:one_time]
end
end

一种控制默认值的方法

class Transaction < ActiveRecord::Base
before_create :set_default_for_type

def set_default_for_type
type = TransactionType.default unless type.present?
end
end

但是 - 最好的方法是只在数据库列上应用默认值,让 ActiveRecord 自动从那里获取它

注意:根据您的情况,仅拥有一个 TransactionType ActiveRecord 对象而不是上面的对象也可能有意义,即

# on Transaction with type_id:integer
belongs_to :type, class_name: "TransactionType"

关于ruby-on-rails - 如何创建枚举类型并默认为新对象的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com