【问题标题】:Ruby script to save records into Rails将记录保存到 Rails 的 Ruby 脚本
【发布时间】:2011-11-04 15:31:33
【问题描述】:

我正在尝试运行一个 ruby​​ 脚本,该脚本解析一个文本文件,每行包含专辑名称、艺术家姓名、年份。然后它应该将新记录保存到名为 Album 的 Rails 模型中。

(buildDB.rb)

fh = File.open('albums.txt')

while line = fh.gets
    if ( line =~ /^(.+)\~\s(.+) \(\'(\d\d)\)/ )
        a = Album.new
        a.name   = $1
        a.artist = $2
        a.year   = $3
        a.save
    end
end

我正在终端中运行 ruby buildDB.rb 来生成消息

buildDb.rb:12:in '<main>': uninitialized constant Album (NameError)

这让我觉得脚本找不到模型。所以我尝试通过使用加载rails环境

require "C:/ruby192/www/Project02/config/environment.rb"

在 ruby​​ 脚本的顶部。该脚本将毫无错误地运行,但不会向 sqlite 数据库提交任何内容。我也可以在已经存在的相册上运行查找,但似乎我无法创建新相册。

我是一个 Rails 菜鸟,所以可能有更好的方法来做到这一点(seeds.rb 或 rake 任务可能)。任何帮助或研究方向将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model terminal


    【解决方案1】:

    我会使用 rake 任务:

    task :create_albums => :environment do
      fh = File.open('albums.txt')
    
      while line = fh.gets
        if ( line =~ /^(.+)\~\s(.+) \(\'(\d\d)\)/ )
          a = Album.new
          a.name   = $1
          a.artist = $2
          a.year   = $3
          a.save!
        end
      end
      fh.close
    end
    

    我添加了一个!到 save 方法,以便任何错误都会引发异常。另外,请确保关闭文件。

    【讨论】:

    • 实际上,刘海的添加给我提供了部分问题。我将模型属性 year 设置为存在 => true,但是从正则表达式返回的年份之一是空的。这在脚本上引发了错误
    • 太棒了!让它工作并了解了一些关于 rake 任务的知识。谢谢drummondj!
    【解决方案2】:

    Rake 任务是前进的方向。我会使用 FasterCSV,因为它会为您处理一些数据导入。

    namespace :import do
      desc "Import from a csv file"
      task :album_csv, [:filename] => :environment do |task, args|
    
      lines = FasterCSV.read(args[:filename]) rescue nil
      if lines
        lines.slice!(0) # remove the CSV header if there is one
        puts "# Processing #{lines.count} records"
        lines.each do |line|
          a = Album.new
          a.name   = line[0]
          a.artist = line[1]
          a.year   = line[2]
          a.save!
        end
      end
    end
    

    然后您可以将您的 rake 任务称为:

    rake import:album_csv[filename]
    

    【讨论】:

      猜你喜欢
      • 2011-06-10
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      相关资源
      最近更新 更多