ruby-on-rails - 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 应用到文件中。
解决方案
最终我想通了,所以希望这对其他人有帮助。我最终添加了 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'
推荐阅读
- dart - Flutter 应用程序在启动时崩溃
- powershell - 调用函数后Powershell发送邮件消息附件与源文件不同
- react-native - 与 Expo 配合使用的 React Native 图像裁剪工具
- haskell - 由于 Paterson 的条件,Haskell 类型类约束无法解决
- c# - 不识别同一命名空间中的接口导入?似乎 MainViewModel 与命名空间 C# 中的其他类隔离
- string - 无法打印字符串自定义内核操作系统
- java - Jetty/javalin 从 websocket 获取 HttpSession 总是返回 null
- javascript - 单击时 div 向下移动
- python - Python ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
- python - 如何使用 minidom + python 更改 XML 中的元素名称