Rails Rake Task放置表并从CSV导入 [英] Rails Rake Task drop table and import from csv
问题描述
我试图编写一个rake任务以删除表并从csv重新填充它。目的是按计划从另一个系统获取数据,并使用rails应用程序管理界面中的按钮导入新数据。这些新数据将覆盖表中的旧数据。
I am trying to write a rake task to drop a table and repopulate it from a csv. The intention is to obtain the data from another system on a schedule, and use a button in the admin interface of my rails application to import the new data. This new data will overwrite the old data in the table.
我不确定如何执行此操作,因此正在处理rake任务。到目前为止,我可以导入新数据,但是我不知道如何首先删除表格。到目前为止,我的代码是:
I am not exactly sure how to do this so am playing around with rake tasks. So far I can import the new data but I can't figure out how to drop the table first. My code so far is:
namespace :csvimportproducts do
desc "Import Products CSV Data."
task :import_products_csv_data => :environment do
ActiveRecord::Migration.drop_table products
require 'csv'
csv_file_path = '/home/jay/workspace/db/import_tables/products.csv'
CSV.foreach(csv_file_path) do |row|
p = Product.create!({
:product_id => row[0],
:product_name => row[1],
}
)
end
end
end
此刻我正在存储本地csv文件,但稍后打算由管理员将其作为csv文件上传。
At the moment I am storing the csv files locally but intend later to have it uploaded by the administrator as a csv file.
有什么想法吗?我的错误是:
Any ideas? My error is:
rake aborted!
undefined local variable or method `products' for main:Object
/lib/tasks/import_products_csv.rake:6:in `block (2 levels) in <top (required)>'
Tasks: TOP => csvimportproducts:import_products_csv_data
推荐答案
尝试通过运行自定义sql命令:
Try by truncating the table by running a custom sql command:
namespace :csvimportproducts do
desc "Import Products CSV Data."
task :import_products_csv_data => :environment do
ActiveRecord::Base.connection.execute("TRUNCATE TABLE products")
require 'csv'
csv_file_path = '/home/jay/workspace/db/import_tables/products.csv'
CSV.foreach(csv_file_path) do |row|
p = Product.create!({
:product_id => row[0],
:product_name => row[1],
}
)
end
end
end
这篇关于Rails Rake Task放置表并从CSV导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!