这是表单上的字段,我正在使用
<%= f.file_field :file ,:url=>{:controller=>"retailers",:action=>"csv_import"}%>
以下是控制器代码
def create
@retailer = Retailer.new(params[:retailer])
respond_to do |format|
if verify_recaptcha(:model =>@retailer ) && @retailer .save
# To notify newly registered user.
retailer_ids = [@retailer.id]
Emailer.on_notify_retailer(retailer_ids, 1, 0)
sign_in @retailer
format.html { redirect_to pages_about_path}
flash[:notice1] = "Thank you for registering with Chindi."
flash[:notice2] = "We will process your application and get back to you within 48 hours. Once approved, you will be able to create negotiable deals that Consumers can tailor to their needs."
flash[:notice3] = "You will be able to create, manage and administer your deals and your buyers in this easy to use control panel."
format.json { render json: pages_about_path, status: :created, location: @retailer }
else
@title = "Sign up"
format.html { render action: "new"}
flash[:notice1] = "Incorrect word verification. Are you sure you\'re human?"
format.json { render json: @retailer.errors, status: :unprocessable_entity }
end
end
csv_parse()
end
以上代码用于将数据保存到数据库中。 CSV文件@retailer.file_file_name
将存储在数据库中,并且需要进行解析,并且值需要存储在字段中
现在我需要解析csv文件并将各个字段存储在另一个数据库中。
csv_parse的代码如下。
def csv_parse
@parsed_file=CSV.foreach(params[:dump][:file].original_filename)
n=0
@parsed_file.each do |row|
User_list.create(
:email=>row[0],
:first_name=>row[1],
:last_name=>row[2]).save
flash.now[:message]="CSV parse Successful, #{n} new records added to data base"
end
end
当我运行它时会出现以下错误/。
当你没想到它时,你有一个零对象!
您可能需要一个Array实例。
评估nil。[]
请帮助我解决上述错误,为什么会抛出这样的错误
提前感谢。
答案 0 :(得分:0)
我只是为我的代码粘贴了一些工作,并希望它能帮到你:
first_line = true
file = File.open File.join(Rails.root, 'tmp/import/category.csv')
file.each do |line|
unless first_line
row = CSV::parse_line(line, ';')
category = Category.find_by_name(row[1]) || Category.create(:name => row[1], :target => 'basic')
category.update_attribute(:import_id, row[0])
else
first_line = false
end
end
我有时写这段代码将类别导入我的数据库。在这里,您可以更改each
迭代器的CSV文件名和块。另外first_line
是对字段的描述,我忽略了它。
答案 1 :(得分:0)
def create
@retailer = Retailer.new(params[:retailer])
respond_to do |format|
# ... same as above
end
csv_parse(params[:retailer][:file].path)
private
def csv_parse(path)
rows = CSV.read(path)
rows.each do |row|
User_list.create(:email=> row[0], :first_name=>row[1], :last_name=>row[2])
end
flash.now[:message]= "CSV parse Successful, #{rows.size} new records added"
end
end