I'm trying to import a standard csv file and all seems to be working ok however, it's just not saving...
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)
. 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. 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. Enter the following code into 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.