2012-12-19 189 views
6

我有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應用程序移動到另一個。

+0

這應該可行,但你需要確保使用'accept_nested_attributes_for'宏 –

回答

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 
1

我採取了一個略有不同的方法,我發現兩個步驟的過程更容易使用和建立。

第一步是加載數據。

我使用兩個'分段'表。
喜歡的東西:

staging_header 
id   Integer Unique Primary Key 
run_number Integer Unique 
run_name  String 

staging_data: 
id     Integer Unique Primary Key 
staging_header_id Integer 
element1   String 
element2   String 
element3   String 
uploaded?   Boolean # Placed on the individual records allows restarts. 
... 

所以我直接加載testimport.csv到這些載物臺 - 支持多種運行,如果你讓run_number獨特(序列等)

現在你有數據在SQL中,並在rails中可用。

現在編寫代碼以實際填充此加載區中的應用程序表。

這也將幫助您解決速度問題。 Rails只會每秒插入幾條記錄,因此您希望能夠重新啓動,暫停等。

這也有助於驗證。最初只需要加載數據,而不管任何約束(非空,唯一等)。

一旦加載到分段中,您可以更具選擇性並根據需要應用驗證。

+0

好了,爲了澄清我的理解,你說你設置了幾個模型並使用類似於我所描述的方法填充它們?然後你使用這些「分段」表填充你的生產模型? –

+0

是的,你的基本方法仍然適用,這種方法確實有助於區分'從csv加載'和'填充表'功能。來自csv的負載可能非常笨,很小。填充表將成爲未來發生變化的表格,附加驗證和業務規則。 –

+0

1例子 - 設想一批記錄,其中1%是'壞'。使用csv加載,您可以更正源代碼,直到所有代碼都很好,然後將其加載到表中。而如果記錄已經直接加載到最終表格中,則會出現更復雜的同步問題,或者刪除記錄,或者找出要拒絕的記錄等。 –