nil的未定义方法`path':NilClass semantic_form_for rails

时间:2015-08-21 17:39:28

标签: ruby-on-rails forms csv import formtastic

我正在尝试使用semantic_form_for上传要解析属性的文件,我似乎无法让它工作,尽管从我读过它应该是。我已经在这一段时间了,似乎无法得到任何工作。

这是我的view.haml:

= semantic_form_for(@user, :url => import_users_path, :html => {:multipart => true} ) do |f|
        = f.inputs :id => 'inputs' do
          = f.input :filename, :as => :file
        %br
        %br
        = f.actions do
          = f.action :submit, :label => 'BULK UPLOAD'

和用户控制器导入功能:

 def import
    myfile = params[:filename]

    CSV.foreach(myfile.path, headers: true) do |row|
      @user = User.new(params[:user])
      @user.name = row['Name']
      @user.email = row['Email']
      @user.save
    end
    redirect_to users_url 
  end

无论出于何种原因,该文件似乎都没有传递给导入功能。它与form_for一起工作正常,但不是semantic_form_for,这是我需要尝试和使用的。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

只需在控制器的导入方法中将myfile = params[:filename]更改为myfile = params[:user][:file]

def import
  myfile = params[:user][:file]

  CSV.foreach(myfile.path, headers: true) do |row|
    @user = User.new
    @user.name = row['Name']
    @user.email = row['Email']
    @user.save
  end
  redirect_to users_url
end

答案 1 :(得分:0)

看起来像是一些网址问题

<% semantic_form_for :post, Post.new, :url => posts_path do |f| %>
  ...
<% end %>

查看http://www.rubydoc.info/gems/formtastic/0.9.10/Formtastic/SemanticFormHelper

试试这个表单会在用户新操作中打开吗?然后......

def new 
 @user = User.new 
end


def import
  CSV.foreach(myfile.path, headers: true) do |row|
    @user = User.new(params[:user])
    @user.name = row['Name']
    @user.email = row['Email']
    @user.save
   end
   redirect_to users_url 
end


<%= semantic_form_for(@user, :url => import_users_path(@user)) do |f| %>

<% end %>