:paperclip: active_admin_import 基于 activerecord-import gem - 这是 ActiveAdmin 导入的最有效方式
:paperclip: active_admin_import 基于 activerecord-import gem - 这是 ActiveAdmin 导入的最有效方式
The fastest and most efficient CSV import for Active Admin with support for validations, bulk inserts, and encoding handling.
Add this line to your application's Gemfile:
gem "active_admin_import"or
gem "active_admin_import" , github: "activeadmin-plugins/active_admin_import"And then execute:
$ bundleActiveAdmin.register Post do
active_admin_import options
end| Tool | Description |
|---|---|
| :back | resource action to redirect after processing |
| :csv_options | hash with column separator, row separator, etc |
| :validate | bool (true by default), perform validations or not |
| :batch_transaction | bool (false by default), if transaction is used when batch importing and works when :validate is set to true |
| :batch_size | integer value of max record count inserted by 1 query/transaction |
| :before_import | proc for before import action, hook called with importer object |
| :after_import | proc for after import action, hook called with importer object |
| :before_batch_import | proc for before each batch action, called with importer object |
| :after_batch_import | proc for after each batch action, called with importer object |
| :on_duplicate_key_update | an Array or Hash, tells activerecord-import to use MySQL's ON DUPLICATE KEY UPDATE or Postgres 9.5+/SQLite 3.24.0+ ON CONFLICT DO UPDATE ability |
| :on_duplicate_key_ignore | bool, tells activerecord-import to use MySQL's INSERT IGNORE or Postgres 9.5+ ON CONFLICT DO NOTHING or SQLite's INSERT OR IGNORE ability |
| :ignore | bool, alias for on_duplicate_key_ignore |
| :timestamps | bool, tells activerecord-import to not add timestamps (if false) even if record timestamps is disabled in ActiveRecord::Base |
| :template | custom template rendering |
| :template_object | object passing to view |
| :result_class | custom ImportResult subclass to collect data from each batch (e.g. inserted ids). Must respond to add(batch_result, qty) plus the readers used in flash messages (failed, total, imported_qty, imported?, failed?, empty?, failed_message). |
| :resource_class | resource class name |
| :resource_label | resource label value |
| :plural_resource_label | pluralized resource label value (default config.plural_resource_label) |
| :error_limit | Limit the number of errors reported (default 5, set to nil for all) |
| :headers_rewrites | hash with key (csv header) - value (db column name) rows mapping |
| :if | Controls whether the 'Import' button is displayed. It supports a proc to be evaluated into a boolean value within the activeadmin render context. |
| :action_item_html_options | HTML options passed to the index-page "Import …" action_item link. Defaults to { class: 'action-item-button' } so the link matches AA 4's built-in action_items; the class is a no-op on AA 3. Override to drop the class or add your own ({ class: 'my-btn' }, { class: '', data: { turbo: false } }, etc.). |
To collect extra data from each batch (for example the ids of inserted rows so you can enqueue background jobs against them), pass a subclass of ActiveAdminImport::ImportResult via :result_class:
class ImportResultWithIds (importer) {
importer.csv_lines.map! { |row| row :post_id)
}
endActiveAdmin.register Post do
active_admin_import validate: true,
template_object: ActiveAdminImport::Model.new(
hint: "expected header order: body, title, author",
csv_headers: %w[body title author]
)
endActiveAdmin.register Post do
active_admin_import validate: true,
template_object: ActiveAdminImport::Model.new(force_encoding: :auto)
endActiveAdmin.register Post do
active_admin_import validate: true,
template_object: ActiveAdminImport::Model.new(
hint: "file is encoded in ISO-8859-1",
force_encoding: "ISO-8859-1"
)
endActiveAdmin.register Post do
active_admin_import validate: true,
template_object: ActiveAdminImport::Model.new(
hint: "upload a CSV file",
allow_archive: false
)
endUseful when the CSV file has columns that don't exist on the table. Available since 3.1.0.
ActiveAdmin.register Post do
active_admin_import before_batch_import: ->(importer) {
importer.batch_slice_columns(['name', 'last_name'])
}
endTip: pass Post.column_names to keep only the columns that exist on the table.
Replace an Author name column in the CSV with the matching author_id before insert:
ActiveAdmin.register Post do
active_admin_import validate: true,
headers_rewrites: { 'Author name': :author_id },
before_batch_import: ->(importer) {
names = importer.values_at(:author_id)
mapping = Author.where(name: names).pluck(:name, :id).to_h
importer.batch_replace(:author_id, mapping)
}
endTwo strategies, depending on your database and whether you need validations.
On databases that support upserts (MySQL, PostgreSQL 9.5+, SQLite 3.24+),
:on_duplicate_key_update updates colliding rows and inserts new ones in a
single statement — no extra delete. The option is passed straight to
activerecord-import, so its shape depends on the adapter:
# PostgreSQL / SQLite
on_duplicate_key_update: { conflict_target: [:id], columns: %i[name last_name birthday] }
# MySQL (infers the key from the columns)
on_duplicate_key_update: %i[name last_name birthday]ActiveAdmin.register Author do
active_admin_import validate: false,
on_duplicate_key_update: { conflict_target: [:id], columns: %i[name last_name birthday] }
endNotes:
validate: false — activerecord-import runs uniqueness validations against the very rows the upsert is about to overwrite, so validates_uniqueness_of would otherwise reject the update.When you can't rely on upsert support — an older database, or you need your model
validations to run — delete the colliding rows just before each batch insert.
The old row is gone before the insert, so validates_uniqueness_of doesn't trip,
at the cost of a second query and full-row replacement (columns absent from
the CSV are reset, not preserved):
ActiveAdmin.register Post do
active_admin_import before_batch_import: ->(importer) {
Post.where(id: importer.values_at('id')).delete_all
}
endActiveAdmin.register Post do
active_admin_import validate: false,
csv_options: { col_sep: ";" },
batch_size: 1000
end…ActiveAdmin.register Post do
active_admin_import validate: false,
template: 'admin/posts/import',
template_object: ActiveAdminImport::Model.new(
hint: "you can configure CSV options",
csv_options: { col_sep: ";", row_sep: nil, quote_char: nil }
)
endapp/views/admin/posts/import.html.erb:
Both before_batch_import and after_batch_import receive the Importer instance:
active_admin_import before_batch_import: ->(importer) {
importer.file # the uploaded file
importer.resource # the ActiveRecord class being imported into
importer.options # the resolved options hash
importer.headers # CSV headers (mutable)
importer.csv_lines # parsed CSV rows for the current batch (mutable)
importer.model # the template_object instance
}| Tool | Description |
|---|---|
| rchardet | Character encoding auto-detection in Ruby. As smart as your browser. Open source. |
| activerecord-import | Powerful library for bulk inserting data using ActiveRecord. |
git checkout -b my-new-feature)git commit -am 'Add some feature')git push origin my-new-feature)暂无开放 Issues,或尚未同步最近议题。