目前我有一个 ActiveAdmin 页面,它从 CSV 文件获取数据以填充数据库表(用户)。该表有一个唯一标识符,该标识符不是关系中使用的ID(供用户查看的用户友好代码)。 该页面通过“active_admin_import”执行此操作
现在,我想要同样的东西填充另一个表(user_paths),问题是,该表使用“users”表中的外键,所以我希望 CSV 文件包含“users”表中的这个唯一标识符.
有什么解决办法吗?
最佳答案
抱歉回复晚了。
就在最近,我向 gem wiki 添加了新示例这与你的问题非常相似。
它可以通过使用 master
分支的自定义 before_batch_import
钩子(Hook)来解决
下一个示例演示如何在执行插入查询之前从作者姓名解析author_id值并动态更改csv值。
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
关于ruby-on-rails - Ruby - ActiveAdmin CSV 自定义导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26131855/