Rails ActiveRecord :: Migration - 将文本文件内容写入数据库

时间:2010-11-30 22:42:58

标签: ruby file 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

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)

3 个答案:

答案 0 :(得分:0)

尝试使用类方法IO.readIO.gets仅在第一个分隔符(通常是换行符)之前读取。

答案 1 :(得分:0)

这里可能存在许多问题。

第一个是检查表中的 body 字段是否有足够的长度来保存文本文件的内容。

此外,获得可能不是你想要的。来自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"))

答案 2 :(得分:0)

IO.read是正确的解决方案