我在用户模型上的一个字段中具有多个复选框。复选框选择当前存储为数组。我正在尝试为用户重新创建“管理”仪表板的编辑视图中的多个复选框,但不确定如何做(文档中的选项似乎并未涵盖这一点)。
这里是迁移引入的领域:
class AddEmploymentTypesToUser < ActiveRecord::Migration[6.0]
def change
add_column :users, :employment_types, :text, array:true, default: []
end
end
该表格的代码:
<div class="form-group">
<label class="font-weight-bold" for="">What type of employment are you looking for?</label>
<br>
<%= f.check_box :employment_types, { :multiple => true }, 'Full-time', nil%> Full-time
<br>
<%= f.check_box :employment_types, { :multiple => true }, 'Part-time', nil%> Part-time
<br>
<%= f.check_box :employment_types, { :multiple => true }, 'Freelance', nil%> Freelance
<br>
<%= f.check_box :employment_types, { :multiple => true }, 'Contract-to-hire', nil%> Contract-to-hire
</div>
Administrate::Field::Base
继承:### app/fields/checkbox_list.rb
class CheckboxList < Administrate::Field::Base
def self.permitted_attribute(attr, _options = nil)
# Yes, this has to be a hash rocket `=>`,
# not a colon `:`. Otherwise it will be the key
# `attr` (literally) as opposed to a key whose name
# is the value of the argument `attr`.
{ attr => [] }
end
def choices
options[:choices]
end
end
对于您的特定情况,我正在实现两种方法。我将分别进行解释。
首先,有self.permitted_attribute
。这是Administrate内部使用的API,用于弄清楚如何将新字段类型转换为params.require(...).permit(...)
的术语。因为您的字段被建模为复选框列表,所以
params
会将其视为数组:
params[:user] # => { name: "Conway Anderson", employment_types: ["Freelance", "Contract-to-hire"] }
要告诉permit
接受此命令,通常可以在Rails应用程序中执行此操作:
params.require(:user).permit(:name, employment_types: [])
[通过像上面一样实现CheckboxList.permitted_attributes
,Administrate传递了正确的信息(employment_types: []
)允许:这就是说允许employment_types
这将是一个数组值。您可能已经在应用程序中的其他位置执行了此操作?
这是第一种方法!现在第二个:choices
。这从options
读取,这是提供给仪表板定义中的字段的选项列表。例如,这里:
ATTRIBUTE_TYPES = { id: Field::Number, name: Field::String, # ... employment_types: CheckboxList.with_options(choices: ['Full-time', 'Part-time', 'Freelance', 'Contract-to-hire']), }.freeze
那样,CheckboxList
可以重新用于不同的选择列表。请注意,我没有使用options
一词,因为Administrate::Field::Base
已在内部使用它,这会发生冲突。
继续,您的字段还需要模板部分,以告诉Rails如何呈现它。它们放在views/
文件夹中,例如可以看起来像这样:
### app/views/fields/checkbox_list/_index.html.erb <%= field.data.join(', ') %>
### app/views/fields/checkbox_list/_show.html.erb
<%= field.data.join(', ') %>
### app/views/fields/checkbox_list/_form.html.erb
<div class="field-unit__label">
<%= f.label field.attribute %>
</div>
<div class="field-unit__field">
<%= f.collection_check_boxes field.attribute, field.choices, :itself, :itself %>
</div>
最棘手的是表格。请注意,我使用的是field.choices
,它与类choices
中定义的方法CheckboxList
相同,并且是从仪表板中提供的选项中读取的。我认为就是这样!将新字段添加到仪表板中(不要忘记将其添加到SHOW_PAGE_ATTRIBUTES
,FORM_ATTRIBUTES
等),您应该会很高兴。