如何在ActiveAdmin中正确配置Rails 4.1枚举 [英] How to Properly Configure Rails 4.1 Enums in ActiveAdmin

查看:152
本文介绍了如何在ActiveAdmin中正确配置Rails 4.1枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的架构中:

  t.integerprivacy_level,默认值:0 

在我的模型中:

 枚举privacy_level:{privacy_private:0,privacy_trusted:1,privacy_public: 2} 

在我的ActiveAdmin注册文件中:

  index do 
列:privacy_level
default_actions
end

form do | f |
f.inputs编辑我的模型do
f.input:privacy_level
end
f.actions
end

在ActiveAdmin索引页上,它的效果很好。每个对象的隐私级别显示为privacy_private,privacy_trusted和privacy_public。



但是,当我尝试编辑对象时,输入类型是一个带有向上和向下箭头的数字框,允许我将任何整数放入,无论整数是否是有效的隐私级别(甚至是负值)。



我想看到的是一个下拉列表(选择)输入,我在模型中定义了三个枚举的字符串值。

解决方案

建立杰克的答案,这是对我有用的。说你的ActiveRecord模型是 Tweets



f.input:privacy_level,as:选择,收藏:Tweet.privacy_levels.keys



这里要注意的关键事项:




  • 您的ActiveRecord有一个有用的字典(可用在enum_name.pluralize)枚举键值。

  • 使用字符串(并忽略基础整数表示)更容易写入枚举值。


I've got a Rails 4.1 app in which I use an enum to represent the privacy level of an object.

In my schema:

t.integer "privacy_level", default: 0

In my model:

enum privacy_level: { privacy_private: 0, privacy_trusted: 1, privacy_public: 2 }

In my ActiveAdmin register file:

index do
  column :privacy_level
  default_actions
end

form do |f|
  f.inputs "Edit My Model" do
    f.input :privacy_level
  end
  f.actions
end

On the ActiveAdmin index page, it works great. The privacy level of each object shows up as "privacy_private", "privacy_trusted", and "privacy_public".

However, when I try to edit an object, the input type is a number box with up and down arrows which allow me to put any integer in, regardless of whether or not the integer is a valid privacy level (even negative values).

What I would like to see is a dropdown (select) input with the three enumerated string values I defined in my model.

解决方案

Building off of Jack's answer, here's what worked for me. Say your ActiveRecord model is Tweets:

f.input :privacy_level, as: :select, collection: Tweet.privacy_levels.keys

Key things to note here:

  • your ActiveRecord has a useful dictionary (available at enum_name.pluralize) of enum keys to values.
  • using strings (and ignoring the underlying integer representation) makes it easier to write to the enum value.

这篇关于如何在ActiveAdmin中正确配置Rails 4.1枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆