首页 > 解决方案 > Rails 在导入 CSV 时插入带有 ID 的列

问题描述

所以我的 Occupant 模型上有以下内容:

def self.import(file)
 CSV.foreach(file.path, headers: true, header_converters: :symbol) do |row|
  Occupant.create! row.to_h
 end
end

在我的 OccupantController 我有

def new
 @occupant = Occupant.new(training_event_id: occupant_params[:training_event_id])
 respond_with @occupant
end
def import
 occupant = Occupant.import(params[:file])
 respond_with @occupant
end

我添加了新方法只是为了表明 Occupant belongs_to TrainingEvent 和 training_event_id 是必需的。现在用户将导入不存在 training_event_id 的数据列表。如何将当前 training_event_id 的列更新/添加到 CSV?

我一直在搞乱 activerecord-import gem,但存在同样的问题,因为我无法弄清楚如何将 TrainingEvent 的当前 ID 添加到模型上的方法中。

编辑:

导入表单存在于 Admin > TrainingEvent > Show 上,并且具有:

=form_tag import_admin_occupants_path, multipart: true do
 =hidden_field_tag :training_event_id, value: @occupant.training_event_id
 =file_field_tag :file
 =submit_tag 'Import'

我想也许我可以在这里插入 training_event_id 但我猜它没有将实际的 id 应用到文件中。

标签: ruby-on-rails

解决方案


最终我想通了,所以希望这对其他人有帮助。我最终添加了 activerecord-import gem 并做了一些小的调整。该表单实际上会将当前的 training_event_id 拉为隐藏字段,因此我将该参数传递给模型/控制器。

目前唯一剩下的问题是让导入后的路线正常工作。但这是一个不同的故事。

乘员模型:

def self.my_import(file, training_event)
 occupants = []
 CSV.foreach(file.path, headers: true, header_converters: :symbol) do |row|
   row['training_event_id'] = training_event
   occupants << Occupant.new(row.to_h)
   occupants.save
 end
 Occupant.import occupants
end

乘员控制器:

def import
 @occupant = Occupant.my_import(params[:file], params[:training_event_id])
 respond_with @occupant, location: admin_training_event_path(@occupant.training_event)
end

管理 > TrainingEvent > 显示

=form_tag import_admin_occupants_path, multipart: true do
 =hidden_field_tag "training_event_id", @training_event.id
 =file_field_tag :file
 =submit_tag 'Import'

推荐阅读