将值读入数组

时间:2012-09-27 14:11:52

标签: ruby-on-rails ruby arrays ruby-on-rails-3 csv

我正在尝试将一些值读入一个.each do代码块中的数组,这是最简单的方法,但我遇到了问题。我正在通过我构建的rake文件导入csv文件,这将使用新行更新表,从而创建新的id。我正在尝试将每个创建的id保存到一个数组中。而且我希望能够在另一个rake任务中访问存储在该数组中的值。

以下代码用于rake文件,该文件将导入csv文件,并且我希望在数组中捕获新生成的id。它目前正在做它应该做的事情,但你一次只能导入一个新行。

Import_incidents_csv.rake

require 'csv'

namespace :import_incidents_csv do

task :create_incidents => :environment do
    puts "Import Incidents"

    csv_text = File.read('c:/rails/thumb/costrecovery_csv/lib/csv_import/incidents.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
        row = row.to_hash.with_indifferent_access
        Incident.create!(row.to_hash.symbolize_keys)
    end

    @last_incident_id = Incident.last.id

    end
  end

这是另一个rake文件导入另一个csv文件,我需要将值存储在分配给的数组中。再说一次,如果你只导入一个新行,它目前工作正常,但如果你导入多行,那么一切都会变得有点乱。

Import_timesheets_csv.rake

require 'csv'

namespace :import_timesheets_csv do

 task :create_timesheets => :environment do
    puts "Import Timesheets"

    csv_text = File.read('c:/rails/thumb/costrecovery_csv/lib/csv_import/timesheets.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
        row = row.to_hash.with_indifferent_access
        Timesheet.create!(row.to_hash.symbolize_keys)
    end

    timesheet = Timesheet.last
    timesheet.incident_id = @last_incident_id
    timesheet.save

    @last_timesheet_id = Timesheet.last.id

     end
end

我读了这个资源来处理数组http://www.tutorialspoint.com/ruby/ruby_arrays.htm,看起来很混乱。以下是我最好猜测Import_incidents_csv.rake文件在将数值读入数组时的样子。而且我最后有了put,所以我可以验证整数是否正确存储在数组中。一旦我把一切都搞定了,我就把它删除了。

require 'csv'

def inc_id
@inc_id = Incident.last.id
end

namespace :import_incidents_csv do

 task :create_incidents => :environment do
    puts "Import Incidents"

    csv_text = File.read('c:/rails/thumb/costrecovery_csv/lib/csv_import/incidents.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
        row = row.to_hash.with_indifferent_access
        Incident.create!(row.to_hash.symbolize_keys)
        Incident.last.id = @inc_id
        id_array = Array.new(@inc_id)
    end

    puts "#{id_array}"

      end
  end

1 个答案:

答案 0 :(得分:2)

我不确定你在这里尝试做什么,你的问题远非明确,但可能是你试图将插入记录的id值收集到一个数组中:

id_array = [ ]

csv.each do |row|
  incident = Incident.create!(row.to_hash.symbolize_keys)
  id_array << incident.id
end

完成此操作后,id_array将包含所有已创建的记录id值。请注意,如果这些create!调用中的任何一个失败,您将获得ActiveRecord::RecordInvalid异常,您需要以某种方式进行救援并进行处理。因此,将整个操作包装在Indcident.transaction do ... end中是有意义的,以确保如果一个失败,假设您的数据库支持事务,则可以回滚整个操作。如果你不关心失败,你可以调用create而不会抛出异常。

您的示例中存在大量冗余,这些冗余已被省略。几乎不需要调用Array.new,因为像JavaScript一样,您可以声明一个新的数组[ ]为空,或者预先填充[ 1 ][ 1, 2 ]

相关问题