Ruby - ActiveAdmin CSV custom import

Currently I have an ActiveAdmin page which gets data from a CSV file to populate a database table (users). This table has one unique identifier which is not the ID used in relationships (a user-friendly code for users to view). The page does this via "active_admin_import"

Now, I want the same thing to populate another table (user_paths), the problem is, this table uses foreign keys from the "users" table, so I want the CSV file to contain this unique identifier from "users" table.

Is there any solution for this?

Upvotes: 2

Views: 2025

Answers (1)

Fivell
Fivell

Reputation: 11929

sorry for late response. Just lately I added new example to gem wiki that is very similar to your problem. It can be solved with custom before_batch_import hook using master branch

Next example demonstrates how to resolve author_id value from author name and change csv values dynamically before performing insert query.

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) #replacing "Jane" with 1, etc
              }
         end

Upvotes: 5

Related Questions