我有3個模型,教會,它有許多地點,其中有許多牧師。一次導入CSV文件到多個模型
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
正如您在我的短代碼塊中所看到的,我正在創建一個教堂及其第一個位置。我怎樣才能讓牧師加入呢?
例如,這項工作?
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
有沒有另一種方法我應該去做這件事?試圖將數千條記錄從一個Rails應用程序移動到另一個。
這應該可行,但你需要確保使用'accept_nested_attributes_for'宏 –