這個代碼可以幫助你......
首先,在lib文件夾命名一個文件:
integer_to_enum.rb
在該文件把這個代碼:
module IntegerToEnum
class << self
def included(klass)
klass.extend(ModelClassMethods)
end
end
module ModelClassMethods
def fields_to_enum(options={})
class_eval <<-end_eval
def set_enum_options
@enum_options = #{options.inspect}
end
end_eval
options.each_pair do |k,v|
class_eval <<-end_eval
def #{k.to_s}
self.set_enum_options
@enum_options[:#{k.to_s}][read_attribute(:#{k.to_s}).to_i]
end
def #{k.to_s}=(v)
self.set_enum_options
unless @enum_options[:#{k.to_s}].include?(v)
return false
end
write_attribute(:#{k.to_s}, @enum_options[:#{k.to_s}].index(v))
@#{k.to_s}
end
end_eval
end
end
end
end
在enviroment.rb,把這個在底部,'結束「
ActiveRecord::Base.send :include, IntegerToEnum
而在去年,在你想要的模型 '翻譯' 的整型字段放:
class YourModel < ActiveRecord::Base
fields_to_enum :appointment_type => [:unknown, :medical, :trial], :other_field_type => [:type_a, :type_b, :type_c]
end
有了這個,你可以這樣做:
m = YourModel.find(1)
m.appointment_type #=> :unknown
m.appointment_type = :trial #=> :trial
m.save #=> and this will save with the index value of the array definition, since ':trial' is in the 3er position, the sql resulting will save with this number
和所有..希望對您有所幫助
我會在哪裏把模塊?在lib /? – intargc 2009-07-24 20:35:57
您可以使用/ lib,但我通常更喜歡使用所有控制器/模型自定義混合創建一個名爲/ apps/concern的文件夾。 – 2009-07-24 21:43:40