有人可以回答如何使用ROR解决以下错误吗?
错误:
NoMethodError in ImagesController#uploadFile
undefined method `[]' for #<ActionDispatch::Http::UploadedFile:0x37973b8>
Extracted source (around line #0):
我的代码片段如下所示。
视图/图像/ index.html.erb
<h1>File Upload</h1>
<%= form_for @image,:url => {:action => 'uploadFile'},
:multipart => true do |f| %>
<p><label for="upload_file">Select File</label> :
<%= f.file_field :datafile %></p>
<%= f.submit "Upload" %>
<% end %>
控制器/ images_controller.rb
class ImagesController < ApplicationController
def index
@image=Image.new
end
def uploadFile
post = Image.save(params[:image][:datafile])
render :text => "File has been uploaded successfully"
end
end
模型/ image.rb
class Image < ActiveRecord::Base
def self.save(upload)
name = upload['datafile'].original_filename
directory = "public/data"
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
end
end
迁移\ 20150115060041_create_images.rb
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :datafile
t.timestamps null: false
end
end
end
请帮我解决上述错误。谢谢。
答案 0 :(得分:0)
拳头,你在控制器中调用这样的保存方法
post = Image.save(params[:image][:datafile])
然后在Image Model里面。 U R再次尝试访问[datafile]
,因为你传递的对象已经是datafile
,因此你得到了错误。
在图像模型中更改此内容
upload['datafile']
至
upload