i did the task of importing csv file to MySql databse. But now my requirements are: 1. Rows and columns of csv file should match with rows and columns of MySql database such that if any row or column is missing, it should raise an error: "Missing @row1 or column 2".. 2. In my code, table header i.e. name, location, city etc; headings are often repeating on every import.
我的法典如下:
def load_csv
end
def import_csv
csv=params[:file].read
n=0
parsed_file = CSV.parse(csv)
parsed_file.each do |row|
i=User.new
i.name = row[0]
i.location = row[1]
i.city = row[2]
if i.valid?
i.save
n=n+1
GC.start if n%50==0
flash[:notice] = "CSV Imported Successfully, with #{n} records"
end
end
In views:
<%= form_for(:user, :url => import_csv_user_path, :html => {:multipart => true}) do |f| %>
<table>
<tr>
<td>
<label for="dump_file">
Select a CSV File :
</label>
</td>
<td ><%= file_field_tag :file -%></td>
</tr>
<tr>
<td colspan= 2 ><%= submit_tag Submit -%></td>
</tr>
</table>
<% end -%>
请帮助我