【发布时间】:2019-01-28 00:40:15
【问题描述】:
我的 rails 应用程序中有一个 CSV 导入功能。我有父母桌和儿童桌。父母与孩子有很多联系。我能够从 CSV 中获取父级详细信息,但无法提取子级详细信息。
parents_controller.rb
def import
@parent = Parent.import(params[:file])
redirect_to main_admin_path, flash: { success: "Parents Imported" }
end
父.rb
has_many :children, dependent: :destroy
def self.import(file)
CSV.foreach(file.path, headers:true) do |row|
Parent.create! row.to_hash
end
end
routes.rb
resources :parents do
collection { post :import }
resources :children
end
main_admin.html.erb
Import Parents
<%= form_tag import_parents_path, multipart:true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import"%>
<% end %>
父.csv
parent_1_firstname,parent_1_lastname,address,childfirstname,childlastname,childdateofbirth
John,Wilson,68 Bell Road,Jessica,Wilson,2002-11-11
John,Wilson,68 Bell Road,Josh,Wilson,2006-10-01
【问题讨论】:
标签: ruby-on-rails csv import ruby-on-rails-5