一次将CSV文件导入多个模型

Aar*_*lls 6 csv activerecord ruby-on-rails

我有3个模型,教堂,有许多地方,有很多牧师.

require 'csv'  
csvfile = File.read("testimport.csv")
csv = CSV.parse(csvfile, :headers => false)
csv.each do |row|
  c = Church.new
     c.name = row[0]
     c.url = row[10]
   c.locations.build(:address => row[3], :zipcode => row[5], :phone => row[6], :email => row[2], :city => row[4])
   c.save
end
Run Code Online (Sandbox Code Playgroud)

正如你在我的短代码中看到的那样,我正在创建一个教堂及其第一个位置.我怎么还要添加牧师呢?

比如这会有用吗?

require 'csv'  
csvfile = File.read("testimport.csv")
csv = CSV.parse(csvfile, :headers => false)
csv.each do |row|
  c = Church.new
     c.name = row[0]
     c.url = row[10]
     location = c.locations.build(:address => row[3], :zipcode => row[5], :phone => row[6], :email => row[2], :city => row[4])
     location.pastors.build(:name => row[10])
     location.save
   c.save
end
Run Code Online (Sandbox Code Playgroud)

我还有另一种方法吗?尝试将数千条记录从一个rails应用程序移动到另一个应用程序.

Aar*_*lls 0

我能够让它工作,以下是我使用的。让我知道是否有更聪明的方法来做到这一点。注意:如果您尝试执行此操作,请将 csv 文件放置在 Rails 目录的根目录中,并在控制台中逐行执行此脚本。至少这就是我让它发挥作用的方式。

require 'csv'  
csvfile = File.read("testimport.csv")
csv = CSV.parse(csvfile, :headers => false)
csv.each do |row|
   c = Church.new
     c.name = row[0]
     c.url = row[10]
   c.locations.build(:title => "Sanctuary", :address => row[3], :zipcode => row[5],     :phone => row[6], :email => row[2], :city => row[4])
   c.save
loc = c.locations.first
loc.pastors.build(:firstname => row[1])
loc.save

end
Run Code Online (Sandbox Code Playgroud)