2010-11-30 3 views
0

나는 약간의 일을하고 있습니다. 여기서는 마이그레이션을 통해 데이터베이스를 채우고 텍스트 파일의 내용을 사용하고 있습니다. 이레일스 ActiveRecord :: Migration - 데이터베이스에 텍스트 파일 내용 쓰기

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

여기에는 여러 가지 문제가있을 수 있습니다.

첫 번째는 테이블의 본문 필드가 텍스트 파일의 내용을 저장할 수있을만큼 충분한 지 확인하는 것입니다.

또한 gets는 내가 본 이후가 아닐 수도 있습니다. RDoc에서 : 당신이 아마 원하는 것은 그것이 기본적으로 파일의 경로를 취할 수 있기 때문에, 당신은 모든 파일을 가져 보장하기 위해 여기 IO.read입니다

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.

, 당신은 파일을 전혀 사용할 필요가 없습니다 여기 :

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를 사용하고 seed/fixtures를 사용하지 않는 이유는 사용자가 .txt 파일을 쓰려고 할 때 (루비 파일이 아닌) 편집하려고하기 때문입니다. –

0

는 클래스 메소드 IO.read 대신를 사용해보십시오? :에 나는 전체 파일을 가져 오지 않습니다 다음과 같은 방법을 사용하고, 누구든지 해결책을 제안 할 수 있습니다. IO.gets은 첫 번째 구분 기호 (일반적으로 개행)까지만 읽습니다.

+1

입니다. – harald

0

IO.read 올바른 솔루션, 당신은 아마 대신 마이그레이션이의`dB/seeds.rb` 파일을 사용한다고 말했다

관련 문제