# app/admin/post.rb
ActiveAdmin.register Post do
permit_params :title, :content, :category_id
form do |f|
f.inputs "Details" do
f.input :title
f.input :content, as: :text
f.input :category
end
actions
end
end
add_new_record_button.js
// app/assets/javascripts/add_new_record_button.js
(function() {
$(function() {
$('select[data-has-new-option=true]').select2({
placeholder: "选择或新建记录",
allowClear: true,
tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newOption: true
}
}
}).on('select2:select', function (e) {
if (e.params.data.newOption) {
var $option = $("")
.val(e.params.data.id)
.text(e.params.data.text);
$(this).append($option).trigger('change');
}
});
});
}).call(this);
# app/assets/javascripts/active_admin.js
//= require active_admin/base
//= require add_new_record_button
# app/admin/category.rb
ActiveAdmin.register Category do
permit_params :name
end
完成这些步骤后,便可以实现添加关联数据的“添加新记录”按钮,用户可以选择现有关联资源或创建新的关联资源。