[英]Import CSV Rails 3 Not Saving
I'm trying to import a standard csv file and all seems to be working ok however, it's just not saving... 我正在尝试导入标准的csv文件,但似乎一切正常,但是,这只是不保存...
I'm trying to import into my customers list and my customer's controller contains: 我正在尝试导入我的客户列表,而我客户的控制者包含:
require 'csv'
and 和
def csv_import
@parsed_file=CSV::Reader.parse(params[:dump][:file])
n=0
@parsed_file.each do |row|
c=Customer.new
c.businessname=row[1]
c.contactname=row[2]
c.address1=row[3]
if c.save
n=n+1
GC.start if n%50==0
end
flash.now[:message]="CSV Import Successful, #{n} new records added to data base"
end
end
On my customer's index page, I have added the following: 在客户的索引页面上,添加了以下内容:
<%= form_for :csv_import, :html => { :multipart => true } do |f| -%>
<table>
<tr>
<td>
<label for="dump_file">
Select a CSV File :
</label>
</td>
<td >
<%= f.file_field :file %>
</td>
</tr>
<tr>
<td colspan='2'>
<%= f.submit "Upload", :disable_with => 'Uploading...' %>
</td>
</tr>
</table>
<% end -%>
When I hit upload, I get redirected to the create customer page and I get an error that says: 当我点击上载时,我被重定向到创建客户页面,并且看到一条错误消息:
Business Name cannot be blank
Which looks though it's not actually saving the data? 哪个看上去并没有实际保存数据?
Any help would be greatly appreciated. 任何帮助将不胜感激。
I think your validations are preventing the save. 我认为您的验证阻止了保存。 In your controller, rather than using
c.save
, try c.save(:validate => false)
. 在您的控制器中,而不是使用
c.save
,请尝试c.save(:validate => false)
。 Let me know how that works out. 让我知道如何解决。
I do not believe ActiveRecord::Base.save
does anything in Rails 3. You need to use the create
method. 我不相信
ActiveRecord::Base.save
在Rails 3中可以做任何事情。您需要使用create
方法。 http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-create http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-create
@parsed_file.each do |row|
Customer.create do |new_cust|
new_cust.attribute_1 = row[1]
new_cust.attribute2 = row[2]
# etc...
end
end
As discussed below, if you're getting expected results and you think your code is right, check the results of the parse in irb. 如下所述,如果您获得了预期的结果,并且您认为代码正确,请检查irb中的解析结果。 Enter the following code into irb.
在irb中输入以下代码。
require 'csv'
path = "c:\path\to\file.csv"
CSV.foreach path do |row|
puts row[0]
puts row[1]
end
If that output looks as expected, then the problem exists elsewhere in your code. 如果该输出看起来像预期的那样,则问题出在代码的其他地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.