Rails导入CSV - 所有值'无'

时间:2012-07-13 17:51:30

标签: ruby-on-rails csv import

我正在学习如何将csv导入rails应用程序。但是,当我运行应用程序时,所有值都变为'nil'。我可以知道下面的代码有什么问题吗?

控制器

def import_csv
    @list = List.find(params[:list_id])
    @lists = List.all

respond_to do |format|
@csv=params[:file]
@n=0
CSV.parse(@csv).each do | row |
  @user_new = User.new
  @user_new.first_name = row[0]
  @user_new.last_name = row[1]
  @user_new.email = row[2]
  @user_new.address = row[3]
  @user_new.city = row[4]
  @user_new.state = row[5]
  @user_new.zipcode = row[6]
  @user_new.country = row[7]
  @user_new.notes = row[8]
  @user_new.birthday = row[9]
  @user_new.home_number = row[10]
  @user_new.mobile_number = row[11]
  @user_new.list_id = @list.id
  @user_new.save

  @n=@n+1
  GC.start if @n%50==0
  flash[:notice] = "CSV Imported Successfully, with  #{@n} records"                                
end

  format.html { redirect_to lists_url }
  format.json { head :no_content }
end

  end

视图

<%= form_for(:list, :url => list_import_csv_path(@list), :method => :get, :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 %>

1 个答案:

答案 0 :(得分:0)

我认为你在表单上发送问题时遇到问题尝试类似这样的事情。 (我的控制器上有一个名为import的自定义操作)

<%= form_tag @list, :action => 'import', :multipart => true do |f| %>

<label class="control-label" for="fileInput" style="width: 160px">Select file: </label>
<%= file_field_tag 'file', :accept => 'text/html', :size => 60%>

<div class="form-actions">
<%= submit_tag 'SUbmit', :class=>"btn" %>
</div>
<% end %>

尝试按照本教程进行导入和导出。Check it out