2010-11-30 14 views
0

我做得稍微非正統這裏,因爲我只是通過遷移填充數據庫,並使用文本文件的內容。我用下面的方法不導入整個文件,任何人都可以提出一個解決這個?:的Rails的ActiveRecord ::遷移 - 寫一個文本文件內容數據庫

class AddChapters < ActiveRecord::Migration

def self.up

Chapter.create!(:title => "chapter 1", 
    :body => File.open("#{Rails.root}/chapters/chapter1.txt").gets) 

Chapter.create!(:title => "Chapter 2", 
    :body => File.open("#{Rails.root}/chapters/chapter2.txt").gets) 

Chapter.create!(:title => "Chapter 3", 
    :body => File.open("#{Rails.root}/chapters/chapter3.txt").gets) 

end

def self.down Chapter.all.each do |chapter| chapter.delete end end end

回答

0

可能有一些在這裏工作的問題。

第一個是檢查表中的正文字段有足夠的長度來容納文本文件的內容。

此外,獲得可能不是你追求的。從的RDoc:

Reads the next ``line’’ from the I/O stream; lines are separated by sep_string. A separator of nil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs). The stream must be opened for reading or an IOError will be raised. The line read in will be returned and also assigned to $_. Returns nil if called at end of file.

你可能想要的是IO.read這裏保證你的所有文件,因爲它可以採取的路徑,默認文件,則不需要使用文件在所有在這裏:

Chapter.create!(:title => "chapter 1", 
    :body => IO.read("#{Rails.root}/chapters/chapter1.txt")) 

Chapter.create!(:title => "Chapter 2", 
    :body => IO.read("#{Rails.root}/chapters/chapter2.txt")) 

Chapter.create!(:title => "Chapter 3", 
    :body => IO.read("#{Rails.root}/chapters/chapter3.txt")) 
+0

很多感謝所有,IO.read的伎倆......我使用.txt和沒有種子/燈具的原因是因爲用戶希望編輯時,他們正在寫一個txt文件,而不是紅寶石文件。 – 2010-12-01 09:12:03

0

嘗試使用類的方法,而不是IO.readIO.gets只讀直到第一個分隔符(通常換行符)。

+1

這就是說,你應該使用`DB/seeds.rb`文件這個,而不是遷移。 – harald 2010-11-30 22:54:23

0

IO.read纔是正確的解決

相關問題