我有简单的上传表格:
<%= 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'为nil:NilClass” 我做错了什么?
我使用Rails 3.0.10和Ruby 1.9.2p290
答案 0 :(得分:1)
答案 1 :(得分:0)
我有这种症状,但间歇性地。有时浏览器(chrome)似乎不会从“选择文件”对话框中选择文件。有一次,我看到双击对话框中的文件后,在浏览器窗口中显示所选文件需要几秒钟。我想如果你在有效选择文件之前点击'submit',那么你会得到那个错误。
<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 %>
答案 2 :(得分: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