Ruby on rails 将enum与administrate集成的正确方法是什么?
我有一个rails应用程序,其中用户有性别,这是一个枚举,其中0表示女性,1表示男性 我在user_dashboard.rb中有以下代码:Ruby on rails 将enum与administrate集成的正确方法是什么?,ruby-on-rails,administrate,rails-administrate,Ruby On Rails,Administrate,Rails Administrate,我有一个rails应用程序,其中用户有性别,这是一个枚举,其中0表示女性,1表示男性 我在user_dashboard.rb中有以下代码: require "administrate/base_dashboard" class UserDashboard < Administrate::BaseDashboard ATTRIBUTE_TYPES = { posts: Field::HasMany, id: Field::Numb
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
需要“管理/基本仪表板”
类UserDashboard
new\u admin\u user\u路径的视图是:
只有管理员可以创建用户,但他们必须手工输入性别,如“男”或“女”。有没有一种方法可以集成一个选择菜单或单选按钮,用于管理gem?一个选项是在属性类型中执行此操作:
ATTRIBUTE_TYPES = {
...
gender: Field::Select.with_options(collection: ["female", "male"]),
}
您也可以尝试AdministrateFieldEnum gem。
假设性别
是您的app/person.rb模型的枚举字段:
class Person < ApplicationRecord
enum gender: { female: 0, male: 1 }
# . . .
end
然后,只需将gender
字段添加到集合属性中,即可显示页面属性数组
Administrate的魔力将处理其余部分,在show和index视图中显示“女性”或“男性”,并在编辑表单中显示select下拉列表
class CreatePersons < ActiveRecord::Migration[6.0]
def change
create_table :persons do |t|
t.integer :gender
# . . .
ATTRIBUTE_TYPES = {
# . . .
gender: Field::Select.with_options(searchable: false, collection: ->(field) { field.resource.class.send(field.attribute.to_s.pluralize).keys }),
# . . .
}