ruby-on-railsadministraterails-administrate

What is the proper way to integrate enum with administrate?


I have a rails app where the users have a gender, which is an enum, where 0 means female and 1 means male.

I have this code in the user_dashboard.rb:

require "administrate/base_dashboard"

class UserDashboard < Administrate::BaseDashboard
    ATTRIBUTE_TYPES = {
        posts: Field::HasMany,
        id: Field::Number.with_options(searchable: false),
        email: Field::String.with_options(searchable: true),
        password: Field::String.with_options(searchable: false),
        password_confirmation: Field::String.with_options(searchable: false),
        encrypted_password: Field::String.with_options(searchable: false),
        reset_password_token: Field::String.with_options(searchable: false),
        reset_password_sent_at: Field::DateTime.with_options(searchable: false),
        remember_created_at: Field::DateTime.with_options(searchable: false),
        first_name: Field::String.with_options(searchable: false),
        last_name: Field::String.with_options(searchable: false),
        gender: Field::Text.with_options(searchable: false),
        type: Field::String.with_options(searchable: false),
        created_at: Field::DateTime.with_options(searchable: false),
        updated_at: Field::DateTime.with_options(searchable: false),
        phone: Field::String.with_options(searchable: false),
    }.freeze

    COLLECTION_ATTRIBUTES = %i[
        posts
        email
        phone
        type
    ].freeze

    SHOW_PAGE_ATTRIBUTES = %i[
        posts
        id
        email
        phone
        first_name
        last_name
        gender
        type
        created_at
        updated_at
    ].freeze

    FORM_ATTRIBUTES = %i[
        posts
        email
        phone
        first_name
        last_name
        gender
        password
        password_confirmation
        type
    ].freeze

    COLLECTION_FILTERS = {}.freeze
end

The view of the new_admin_user_path is: enter image description here

Only admins can create users, but they have to type out the gender like "male" or "female" by hand. Is there a way to integrate a select menu or radio buttons that will work with administrate gem?


Solution

  • One option is to do this in your ATTRIBUTE_TYPES:

    ATTRIBUTE_TYPES = {
      ...
      gender: Field::Select.with_options(collection: ["female", "male"]),
    }
    

    You might also try the AdministrateFieldEnum gem. https://github.com/valiot/administrate-field-enum