36

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.

Pop-A-Stash
  • 6,572
  • 5
  • 28
  • 54

3 Answers3

60

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.
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
AlexeyMK
  • 6,245
  • 9
  • 36
  • 41
40

In order to use enums in ActiveAdmin's filters use:

filter :level, as: :select, collection: Model.levels

assuming an enum attribute named level

This will make sure to actually put the integer value in the query and not the key name.

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
ChrHansen
  • 1,502
  • 1
  • 14
  • 22
7

do this:

f.input :privacy_level, :as => :select, :collection =>  privacy_level.keys.to_a
jimagic
  • 4,045
  • 2
  • 28
  • 49
  • Yeah, that makes sense. I can set privacy level in the console with my_model.privacy_level = "privacy_public". It would make sense that I can use a select box with strings to set the privacy level. Thanks! – Pop-A-Stash May 01 '14 at 20:42
  • 2
    you welcome, glad to help, i have upvoted your question so u can get the point, please do same for me, thanks – jimagic May 01 '14 at 20:45