[英]How do I test if an ActiveRecord attribute is an Enum?
How would I test if an ActiveRecord attribute is an Enum?我将如何测试 ActiveRecord 属性是否为 Enum? (as per Rails 4.1 enum declaration) (根据 Rails 4.1 枚举声明)
It's stored in the database and using the type method on columns_hash identifies the attribute as an integer.它存储在数据库中,并使用 columns_hash 上的 type 方法将该属性标识为整数。
Enum definition in model模型中的枚举定义
enum status: [ :in_progress, :accepted, :approved, :declined, :closed, :cancelled, :submitted ]
To pull the type拉类型
irb(main):030:0> Application.columns_hash['status'].type
=> :integer
ActiveRecord::Enum
adds a defined_enums
class attribute to the model - a hash storing the defined enums: ActiveRecord::Enum
向模型添加了一个defined_enums
类属性 - 一个存储定义的枚举的哈希:
MyModel.defined_enums
#=> {"status"=>{"in_progress"=>0, "accepted"=>1, "approved"=>2, "declined"=>3, "closed"=>4, "cancelled"=>5, "submitted"=>6}}
To test if an attribute is an enum you could use:要测试属性是否是枚举,您可以使用:
MyModel.defined_enums.has_key?('status')
#=> true
Unfortunately, defined_enums
is not documented.不幸的是,没有记录defined_enums
。
I kept on finding this answer when trying to figure out how to do this, but @stefan's method was giving me an uninitialized constant PostsHelper::Application
在试图弄清楚如何做到这一点时,我一直在寻找这个答案,但@stefan 的方法给了我一个uninitialized constant PostsHelper::Application
Found this also works:发现这也有效:
Post.type_for_attribute(attribute).is_a
Possibly a bit cleaner, since you don't have to worry about _prefix
and _suffix
?可能更干净一点,因为您不必担心_prefix
和_suffix
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.