我正在构建一个新模型,我想添加一个属于选择器的属性。你怎么做到这一点?什么是班级?
我有标准:整数,:datetime等。
我想要一个类型:
选择器会有多种选择['运行','骑','驱动器''飞']
感谢
答案 0 :(得分:3)
红宝石中没有类,最接近的是:
class YourModel < ActiveRecord::Base
MyOptions = ['run', 'ride', 'drive', 'fly']
validates :my_attributes, inclusion: {in: MyOptions}
end
如果您想更进一步,如果值不在允许的值中,您可以覆盖setter以引发异常:
class InvalidValue < StandardError
end
def my_attribute=(value)
raise InvalidValue.new unless MyOptions.include?(value)
super
end
答案 1 :(得分:0)
loads different solutions available用于在Rails模型中实现可枚举属性。
这些问题倾向于从与BroiSatse的答案相同的角度处理问题,但提供更全面的验证,辅助方法等。
查看这些链接,看看哪种最适合您的需求。
https://github.com/electronick/enum_column
https://github.com/jeffp/enumerated_attribute
答案 2 :(得分:0)
Camelcase是类名的约定。我会选择一个常数:
MY_OPTIONS = %w(run ride drive fly).freeze