简体   繁体   English

如何测试 ActiveRecord 属性是否为 Enum?

[英]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.

相关问题 如何在Cucumber中测试ActiveRecord引用? - How do I test ActiveRecord references in Cucumber? 如何在ActiveRecord模型中验证虚拟属性? - How do I validate a virtual attribute in an ActiveRecord model? 如何在 Rails ActiveRecord 查询中引用不同属性的值 - How do I reference the value of a different attribute in a Rails ActiveRecord Query 如何将ActiveRecord模型属性从json迁移到jsonb? - How do I migrate an ActiveRecord model attribute from json to jsonb? 如何使Rails ActiveRecord依赖于属性? - How do I make a Rails ActiveRecord dependent on an attribute? 如何测试使用不同数据库修改ActiveRecord的gem? - How do I test a gem that modifies ActiveRecord with different DB's? 如何测试ActiveRecord创建块内的行为? - How do I test the behavior inside an ActiveRecord creation block? 如何查询 ActiveRecord 以仅返回每个 object 的第一个实例,其中 enum = X、Y、Z? - How do I query ActiveRecord to return only the first instance of each object where enum = X, Y, Z? 我可以测试ActiveRecord的属性是否为外键吗? - Can I test whether an ActiveRecord's attribute is a foreign key? 在 Rails 3.2(多对多)中使用 .build 方法时,如何设置 ActiveRecord model 属性 - How do I set ActiveRecord model attribute when using .build method with Rails 3.2 (many-to-many)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM