Search code examples
ruby-on-railsruby-on-rails-4activeadminformtastic

ActiveAdmin how to display values in dropdown but store keys to db


How can I display the string name, but save the integer key to the db in a dropdown in active admin? I have this form:

form do |f|
  f.inputs "Status" do
    f.input :status, as: :select, collection: App::STATUSES.keys
  end
  f.actions
end

which produces this and works fine: enter image description here

but I need it to produce this: enter image description here

This is the code which produces the above image. It displays the values that I want, but it doesn't save the keys (0, 1, 2, etc.) to the db

form do |f|
  f.inputs "Status" do
    f.input :status, as: :select, collection: App::STATUSES.values
  end
  f.actions
end

I tried this but it doesn't work:

form do |f|
  f.inputs "Status" do
    f.input :status, as: :select, collection: App::STATUSES.values, :label_method => :status_name
  end
  f.actions
end

Here is my model:

IN_PROGRESS = 0 #default
SUBMITTED = 1
REVIEW = 2
PENDING = 3
APPROVED = 4
LIVE = 5


STATUSES = {
  IN_PROGRESS => 'in progress',
  SUBMITTED => 'submitted',
  REVIEW => 'review',
  PENDING => 'pending',
  APPROVED => 'approved',
  LIVE => 'live'
}

def status_name
  STATUSES[status].to_s
end

The status_name method works fine throughout my app, it just doesn't get called for some reason when displaying the dropdown.


Solution

  • try use your hash as collection (or inverted hash)

     f.input :status, as: :select, collection: App::STATUSES.invert, :label_method => :status_name