Rails4.1以前のEnum

Rails4.1以降はEnum使えますし素晴らしい記事をありがとうございます。

外部キーみたいに数字でステータスを持たせるけどデータベース側にはマスタを持たせないっていうときに書いたもののメモ。

今使っているのRailsは4.0.4なので、自力でモデルにハッシュを書いて、viewではoptions_for_selectでパスーンと組み立てています。

こんな感じで区分値を持たせて

class SupplierStockType
    AMPLE_STOCK  = {:id => 1, :name => I18n.t('ample_stock')}
    SMALL_STOCK  = {:id => 2, :name => I18n.t('small_stock')}
    NOT_IN_STOCK = {:id => 3, :name => I18n.t('not_in_stock')}

  def self.all
    self.constants.map { |value| const_get(value) }
  end

end

view/helper側でこう組み立てる

options_for_select(SupplierStockType.all.collect {|p| [ p[:name], p[:id] ] })