Administrate: Enum fields

Created on 4 Apr 2016  Â·  8Comments  Â·  Source: thoughtbot/administrate

It would be really useful to have some way to entry values for has_entry.

Most helpful comment

rails g administrate:field enum

enum_field.rb

require "administrate/field/base"

class EnumField < Administrate::Field::Base
  def to_s
    data
  end

  def select_field_values(form_builder)
    form_builder.object.class.public_send(attribute.to_s.pluralize).keys.map do |v|
      [v.titleize, v]
    end
  end
end

_form.html.erb

<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.select field.attribute, field.select_field_values(f) %>
</div>

(_show/_index).html.erb

<%= field.to_s.titleize %>

All 8 comments

rails g administrate:field enum

enum_field.rb

require "administrate/field/base"

class EnumField < Administrate::Field::Base
  def to_s
    data
  end

  def select_field_values(form_builder)
    form_builder.object.class.public_send(attribute.to_s.pluralize).keys.map do |v|
      [v.titleize, v]
    end
  end
end

_form.html.erb

<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.select field.attribute, field.select_field_values(f) %>
</div>

(_show/_index).html.erb

<%= field.to_s.titleize %>

@hauleth Does the custom field that @stevenpetryk illustrated above work for your needs? If so, would you or he like to take a stab at creating it as a plugin?

Here's an example:
https://github.com/thoughtbot/administrate-field-image

Worked for me. You might want to change EnumField#to_s to

def to_s
  data.to_s
end

In case the enum data is nil

@stevenpetryk what is the benefit over Field::Select.with_options(collection: Model::ENUM) ?

@carsonbland I'm not sure – it may very well be the case that that was undocumented/impossible back when I posted that response. If that works, then go for it!

Closing this, since a custom enum field with bin/rails g administrate:field enum solves the issue.

@stevenpetryk great solution! Thanks!!

@BenMorganIO Sounds like this should be part of core

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kwerle picture kwerle  Â·  4Comments

brynmrk picture brynmrk  Â·  3Comments

MatthiasRMS picture MatthiasRMS  Â·  3Comments

drewtunney picture drewtunney  Â·  3Comments

rmarronnier picture rmarronnier  Â·  4Comments