使用 ruby​​ CSV 模块导入 csv 文件时出现问题

发布于 2024-09-18 16:41:19 字数 795 浏览 13 评论 0原文

我正在尝试使用 Ruby 的 csv 模块将 csv 文件中包含的记录导入到 Ruby on Rails 3 应用程序中的本地表中。

该表是通过创建模型 Movie 来创建的。

以下是我在控制台中执行的操作:

require 'csv'
CSV.foreach('public/uploads/VideoTitles2.csv') do |row|
    record = Movie.new(
        :media_format   => row[0], 
        :title          => row[1], 
        :copies_at_home => row[2], 
        :order          => row[3]
    )
    record.save
end

csv 文件的行与它们传递到的列相匹配(在数据类型中)。这是我尝试导入的 csv 文件 (VideoTitles2.csv) 的缩短版本:

"DVD","LEAP OF FAITH",1,1
"DVD","COCOON",1,2
"DVD","TITANIC",1,3

我相信每条记录均以 \n 分隔。此 csv 文件是从 Access 导出的,其原始文件扩展名为 .txt。为了导入,我已手动将其更改为 .csv。

问题是,在 Rails 控制台中执行上述行后,我得到以下输出:

=> nil

导入似乎没有发生。如果有人知道如何解决这个问题,我将非常感激。

I'm trying to use Ruby's csv module to import the records contained in a csv file to my local table in a Ruby on Rails 3 application.

The table was created through the creation of model Movie.

Here is what I've been executing in console:

require 'csv'
CSV.foreach('public/uploads/VideoTitles2.csv') do |row|
    record = Movie.new(
        :media_format   => row[0], 
        :title          => row[1], 
        :copies_at_home => row[2], 
        :order          => row[3]
    )
    record.save
end

The rows of the csv file match (in data type) the columns they're being passed into. Here is a shortened version of the csv file (VideoTitles2.csv) I'm attempting to import:

"DVD","LEAP OF FAITH",1,1
"DVD","COCOON",1,2
"DVD","TITANIC",1,3

where each record is separated by \n I believe. This csv file was exported from Access and its original file extension was .txt. I've manually changed it to .csv for sake of the import.

The problem is that, after executing the above lines in rails console, I get the following output:

=> nil

The import doesn't seem to happen. If anyone has an idea as to how I could remedy this I'd really appreciate it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空‖城人不在 2024-09-25 16:41:19

我没有看到问题所在。此代码片段返回 nil,因为 CSV.foreach 返回 nil,但这并不指示循环是否运行。您是否检查过是否创建了任何Movie?您是否包含任何调试行来跟踪该过程?

您可能想要检查 record.save 的输出(或调用 record.save!),也许验证错误阻止了记录的创建。另外,如果你想让循环返回创建的记录,你可以这样写(Ruby >= 1.8.7):

require 'csv'

records = CSV.foreach('public/uploads/VideoTitles2.csv').map do |media_format, title, copies_at_home, order|     
    Movie.create!({
        media_format: media_format, 
        title: title, 
        copies_at_home: copies_at_home, 
        order: order,
    })
end

I don't see the problem. This code snippet returns nil because CSV.foreach returns nil, but this is no indication if the loop is run or not. Did you checked if any Movie was created? did you include any debug lines to follow the process?

You may want to check the output of record.save (or call record.save!), maybe validations errors are preventing the record from being created. Also, if you want the loop to return the created records, you can write this (Ruby >= 1.8.7):

require 'csv'

records = CSV.foreach('public/uploads/VideoTitles2.csv').map do |media_format, title, copies_at_home, order|     
    Movie.create!({
        media_format: media_format, 
        title: title, 
        copies_at_home: copies_at_home, 
        order: order,
    })
end
苍白女子 2024-09-25 16:41:19

好吧,我有两件事错了:

  1. 导出的 csv 文件不应在字符串周围包含引号 - 我刚刚删除了它们。

  2. 感谢 tokland,记录。保存!是必要的(与我正在执行的 record.save 相反) - 验证错误阻止了创建记录。

总而言之,可以在创建模型/表 Movie 后创建以下函数:

class Movie < ActiveRecord::Base
  attr_accessible :media_format, :title, :copies_at_home, :order
  require 'csv'

  def self.import_movies()
    CSV.foreach('public/uploads/movies.csv') do |row|
        record = Movie.new(
            :media_format   => row[0], 
            :title          => row[1], 
            :copies_at_home => row[2], 
            :order          => row[3]
        )
        record.save!  
    end
  end
end

其中 movie.csv 如下所示:

Blu-ray, Movie 1, 1, 1
DVD, Movie 2, 1, 2
Blu-ray, Movie 3, 1, 3

然后在控制台中调用此函数:

Movie.import_movies()

正如预期的那样,所有内容都将在控制台中返回将是:

=> nil

检查您的索引视图(如果您已经创建了索引视图),您应该看到记录已成功导入到电影表中。

Okay there were two things I had wrong:

  1. The exported csv file should not have quotations around the strings - I just removed them.

  2. Thanks to tokland, the record.save! was necessary (as opposed to the record.save I was doing) - validation errors were preventing the records from being created.

So to conclude, one could just create the following function after creating the model/table Movie:

class Movie < ActiveRecord::Base
  attr_accessible :media_format, :title, :copies_at_home, :order
  require 'csv'

  def self.import_movies()
    CSV.foreach('public/uploads/movies.csv') do |row|
        record = Movie.new(
            :media_format   => row[0], 
            :title          => row[1], 
            :copies_at_home => row[2], 
            :order          => row[3]
        )
        record.save!  
    end
  end
end

Where movies.csv looks like the following:

Blu-ray, Movie 1, 1, 1
DVD, Movie 2, 1, 2
Blu-ray, Movie 3, 1, 3

then call this function in console as such:

Movie.import_movies()

and, as expected, all that would be returned in the console would be:

=> nil

Check your index view (if you've created one) and you should see that the records were successfully imported into the movies table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文