Skip to content

change columns on the fly by association

Igor Fedoronchuk edited this page Jan 21, 2015 · 2 revisions

change csv values before import, find each author by 'Author name' and replace it with its id before insert

 ActiveAdmin.register Post  do
             active_admin_import validate: true,
              headers_rewrites: { :'Author name' => :author_id },
              before_batch_import: ->(importer) {
                authors_names = importer.values_at(:author_id)
                # replacing author name with author id
                authors   = Author.where(name: authors_names).pluck(:name, :id)
                options = Hash[*authors.flatten] # #{"Jane" => 2, "John" => 1}
                importer.batch_replace(:author_id, options)
              }
         end

Clone this wiki locally