2011-11-02 26 views
2

我有簡單的上傳方式:Rails的文件上傳錯誤 「未定義的方法`original_filename」的零:NilClass」

<%= form_for(:product, :url => {:action => 'update_product', :id => @product.id}, :html => {:multipart => true}) do |f| %> 
<%= f.file_field(:product_image) %> 
<%= submit_tag('Upload') %> 
<% end %> 

並在控制器:

def update_product 
    product = Product.find(params[:id]) 
    if(product) 
     uploaded_image = params[:product][:product_image] 
     params[:product][:product_image] = uploaded_image.original_filename 
     product.update_attributes(params[:product]) 
     flash[:notice] = "Successfully updated!" 
     redirect_to :action => 'edit_product', :id => product.id 
    end 
end 

當我嘗試上傳,有一個錯誤「未定義的方法`original_filename'爲零:NilClass」 我做錯了什麼?

我使用Rails的3.0.10和Ruby 1.9.2p290

回答

1

我的猜測是PARAMS [:產品] [:product_image]爲零。

嘗試使用gem進行文件上傳。

來源

1.Paperclip

2.Carrierwave

0

我有這個症狀,但間歇性。有時瀏覽器(chrome)似乎不會從「選擇文件」對話框中選擇文件。有一次,我看到雙擊對話框中的一個文件後,它花了幾秒鐘的時間將所選文件顯示回瀏覽器窗口。我猜如果你在文件被有效選擇之前點擊'提交',那麼你會得到這個錯誤。

 <h2>Choose file to upload ...</h2> 
<%= form_tag({:action => :sched_file_uploader}, :multipart => true) do %> 
    <%= file_field_tag 'schedfile' %> 
    </br></br> 
    <%= text_area_tag(:file_info, "<care to say anything about this file?>", :size => "24x6") %> 
    </br></br> 
    <input name="upload" type="submit" value="Upload" /> 
<% end %> 
0

請刪除此行:

params[:product][:product_image] = uploaded_image.original_filename 

def update_product 
    product = Product.find(params[:id]) 
    if(product) 
     uploaded_image = params[:product][:product_image].original_filename 
     product.update_attributes(params[:product]) 
     flash[:notice] = "Successfully updated!" 
     redirect_to :action => 'edit_product', :id => product.id 
    end 
end 
相關問題