I know this question has been asked a lot on this forum but I'm under a strict deadline and I need some help, so any advice is much appreciated. I'm new to Ruby on Rails so please keep that in mind when responding. I want to create a rake task that, when run, updates multiple tables in mysqlite db. This is a migration file that creates a new incident in my db. How do I create a rake task that will input all this info via a CSV file. Can someone PLEASE give me some help in writing the rake file from start to finish. Obviously you don't need to write every task for every string, just give me a few examples. And besides the actual rake file, do I need to add code to any other part of my app (I know thats a very general question, but if I do need to add code, I would appreciate a general description of where). I feel a little bit of guidance will go along way. If anyone needs any more information from me please just ask.
我知道这个问题已经在这个论坛上被问了很多,但是我在一个严格的截止日期之前,我需要一些帮助,所以任何建议都非常感谢。我是Ruby on Rails的新手,所以请在回复时记住这一点。我想创建一个rake任务,在运行时,更新mysqlite db中的多个表。这是一个在我的数据库中创建新事件的迁移文件。如何创建rake任务,通过CSV文件输入所有这些信息。有人可以从头到尾写一些rake文件给我一些帮助。显然你不需要为每个字符串编写每个任务,只需举几个例子。除了实际的rake文件之外,我是否需要将代码添加到我的应用程序的任何其他部分(我知道这是一个非常普遍的问题,但如果我确实需要添加代码,我将非常感谢对其中的一般描述)。我觉得会有一些指导意见。如果有人需要我的任何更多信息,请询问。
class CreateIncidents < ActiveRecord::Migration
def self.up
create_table :incidents do |t|
t.datetime :incident_datetime
t.string :location
t.string :report_nr
t.string :responsible_party
t.string :area_resident
t.string :street
t.string :city
t.string :state
t.string :home_phone
t.string :cell_phone
t.string :insurance_carrier_name
t.string :insurance_carrier_street
t.string :insurance_carrier_city
t.string :insurance_carrier_state
t.string :insurance_carrier_phone
t.string :insurance_carrier_contact
t.string :policy_nr
t.string :vin_nr
t.string :license_nr
t.string :vehicle_make
t.string :vehicle_model
t.string :vehicle_year
t.timestamps
end
end
def self.down
drop_table :incidents
end
end
5 个解决方案
#1
20
under your project folder in lib/task create a rake file say "import_incidents_csv.rake"
在lib / task的项目文件夹下创建一个rake文件,说“import_incidents_csv.rake”
follow this Ruby on Rails - Import Data from a CSV file
遵循这个Ruby on Rails - 从CSV文件导入数据
in rake file have following code
在rake文件中有以下代码
require 'csv'
namespace :import_incidents_csv do
task :create_incidents => :environment do
"code from the link"
end
end
You can call this task as "rake import_incidents_csv:create_incidents"
您可以将此任务称为“rake import_incidents_csv:create_incidents”
#2
11
I worked on this for hours and hours one day. I finally got it to work by doing the following:
我有一天工作了几个小时。我终于通过以下方式让它工作:
- Added a header in the first row to my csv file that reflected the
attr_accessible
in my model. In my case my model wasattr_accessible
:intro
,:name
and in my csv file the first line read name, intro. - 在我的csv文件的第一行添加了一个标题,反映了我的模型中的attr_accessible。在我的情况下,我的模型是attr_accessible:intro,:name和我的csv文件中的第一行读取名称,简介。
- Created a custom rake file. I named mine import.rake and placed it in the lib/tasks folder. Place this code in that file:
- 创建了自定义rake文件。我将其命名为import.rake并将其放在lib / tasks文件夹中。将此代码放在该文件中:
#lib/tasks/import.rake require 'csv' desc "Imports a CSV file into an ActiveRecord table" task :import, [:filename] => :environment do CSV.foreach('myfile.csv', :headers => true) do |row| MyModel.create!(row.to_hash) end end
Then type bundle exec rake import
into the command line.
然后在命令行中键入bundle exec rake import。
To get this to work I had quite SQLite Database Browser. I hope that helps someone!
为了使这个工作,我有相当SQLite数据库浏览器。我希望能帮助别人!
#3
2
Here is an example CSV that I imported using rake db:seed. I wrote this into the seeds.rb file and put the CSV file into /public/seed_data/zip_code.csv. It's pretty self explanatory (i.e., the csv has three columns: code, long. and lat.
这是我使用rake db:seed导入的示例CSV。我将其写入seeds.rb文件并将CSV文件放入/public/seed_data/zip_code.csv。这是非常自我解释的(即,csv有三列:代码,长和。纬度。
The code parses each line, extracts the pertinent data and assigns it to a local variable then writes it to a record. Hope it helps.
代码解析每一行,提取相关数据并将其分配给局部变量,然后将其写入记录。希望能帮助到你。
File.open("#{Rails.root}/public/seed_data/zip_code.csv") do |zip_codes|
zip_codes.read.each_line do |zip_code|
code, longitude, latitude = zip_code.chomp.split(",")
# to remove the quotes from the csv text:
code.gsub!(/\A"|"\Z/, '')
# to create each record in the database
ZipCodeGeo.create!(:zip_code => code, :longitude => longitude, :latitude => latitude)
end
end
#4
0
You can read your csv file using CSV
module of rails and can create records. Here is detailed help: Populate db using csv
您可以使用rails的CSV模块读取csv文件,并可以创建记录。以下是详细的帮助:使用csv填充数据库
#5
0
I've used this one in the past. It takes any type of model.
我过去曾经用过这个。它需要任何类型的模型。
rake csv_model_import[bunnies.csv,Bunny]
Works like a charm.
奇迹般有效。
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, :filename, :model, :needs => :environment do |task,args|
lines = File.new(args[:filename]).readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
params = {}
values = line.strip.split(',')
keys.each_with_index do |key,i|
params[key] = values[i]
end
Module.const_get(args[:model]).create(params)
end
end
#1
20
under your project folder in lib/task create a rake file say "import_incidents_csv.rake"
在lib / task的项目文件夹下创建一个rake文件,说“import_incidents_csv.rake”
follow this Ruby on Rails - Import Data from a CSV file
遵循这个Ruby on Rails - 从CSV文件导入数据
in rake file have following code
在rake文件中有以下代码
require 'csv'
namespace :import_incidents_csv do
task :create_incidents => :environment do
"code from the link"
end
end
You can call this task as "rake import_incidents_csv:create_incidents"
您可以将此任务称为“rake import_incidents_csv:create_incidents”
#2
11
I worked on this for hours and hours one day. I finally got it to work by doing the following:
我有一天工作了几个小时。我终于通过以下方式让它工作:
- Added a header in the first row to my csv file that reflected the
attr_accessible
in my model. In my case my model wasattr_accessible
:intro
,:name
and in my csv file the first line read name, intro. - 在我的csv文件的第一行添加了一个标题,反映了我的模型中的attr_accessible。在我的情况下,我的模型是attr_accessible:intro,:name和我的csv文件中的第一行读取名称,简介。
- Created a custom rake file. I named mine import.rake and placed it in the lib/tasks folder. Place this code in that file:
- 创建了自定义rake文件。我将其命名为import.rake并将其放在lib / tasks文件夹中。将此代码放在该文件中:
#lib/tasks/import.rake require 'csv' desc "Imports a CSV file into an ActiveRecord table" task :import, [:filename] => :environment do CSV.foreach('myfile.csv', :headers => true) do |row| MyModel.create!(row.to_hash) end end
Then type bundle exec rake import
into the command line.
然后在命令行中键入bundle exec rake import。
To get this to work I had quite SQLite Database Browser. I hope that helps someone!
为了使这个工作,我有相当SQLite数据库浏览器。我希望能帮助别人!
#3
2
Here is an example CSV that I imported using rake db:seed. I wrote this into the seeds.rb file and put the CSV file into /public/seed_data/zip_code.csv. It's pretty self explanatory (i.e., the csv has three columns: code, long. and lat.
这是我使用rake db:seed导入的示例CSV。我将其写入seeds.rb文件并将CSV文件放入/public/seed_data/zip_code.csv。这是非常自我解释的(即,csv有三列:代码,长和。纬度。
The code parses each line, extracts the pertinent data and assigns it to a local variable then writes it to a record. Hope it helps.
代码解析每一行,提取相关数据并将其分配给局部变量,然后将其写入记录。希望能帮助到你。
File.open("#{Rails.root}/public/seed_data/zip_code.csv") do |zip_codes|
zip_codes.read.each_line do |zip_code|
code, longitude, latitude = zip_code.chomp.split(",")
# to remove the quotes from the csv text:
code.gsub!(/\A"|"\Z/, '')
# to create each record in the database
ZipCodeGeo.create!(:zip_code => code, :longitude => longitude, :latitude => latitude)
end
end
#4
0
You can read your csv file using CSV
module of rails and can create records. Here is detailed help: Populate db using csv
您可以使用rails的CSV模块读取csv文件,并可以创建记录。以下是详细的帮助:使用csv填充数据库
#5
0
I've used this one in the past. It takes any type of model.
我过去曾经用过这个。它需要任何类型的模型。
rake csv_model_import[bunnies.csv,Bunny]
Works like a charm.
奇迹般有效。
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, :filename, :model, :needs => :environment do |task,args|
lines = File.new(args[:filename]).readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
params = {}
values = line.strip.split(',')
keys.each_with_index do |key,i|
params[key] = values[i]
end
Module.const_get(args[:model]).create(params)
end
end