1

I have a model

class Transaction < ActiveRecord::Base

end

I have a transaction_type column which is an integer.

How can I create an enumeration that I could map values to names like:

one_time = 1
monthly = 2
annually = 3

So in the db column, the values would be 1, 2 or 3.

Also, whenever I create a new instance, or save a model and the field wasn't set like:

@transaction = Transaction.new(params)

It should default to 1 (on_time).

I'm not sure how I can do this?

4

3 回答 3

4

与 Amit 的答案基本相同,略有不同

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" 
于 2013-11-14T20:45:10.073 回答
2

您可以通过在同一Transaction模型中创建常量或通过创建新模块并将其放置在其中来映射值,如@KepaniHaole 所述

Transaction模型中,您可以这样做:

class Transaction < ActiveRecord::Base

  TRANSACTION_TYPES = { 'one_time' => 1, 'monthly' => 2, 'monthly' => 3 }

end

您可以通过访问常量来访问这些值

Transaction::TRANSACTION_TYPES['one_time']    # => 1
Transaction::TRANSACTION_TYPES['monthly']     # => 2
Transaction::TRANSACTION_TYPES['monthly']     # => 3

要为transaction_type列添加默认值,只需使用以下命令创建一个新迁移:

def up
  change_column :transactions, :transaction_type, :default => Transaction::TRANSACTION_TYPES['one_time']
end

有了这个,每次你创建一个Transaction没有传递的对象时transaction_type,默认值 1 都会被存储在其中。

于 2013-11-14T18:59:26.577 回答
1

也许你可以尝试这样的事情?Ruby 并不真正支持 c 风格的枚举。

module TransactionType
  ONCE = 1
  MONTHLY = 2
  ANUALLY = 3
end

那么您可以像这样访问它们的值:

@transaction = Transaction.new(TransactionType::ONCE)
于 2013-11-14T18:43:24.897 回答