我有一个非常简单的上传文件配置。我只是想将带有描述的图像上传到数据库(我知道,我知道......)。就是这样。
这是我的模型的样子(我从这里学到的)。基本上,这正是示例的设置方式,只是使用attr_protected
Rails 3.2 的行:
Photo < ActiveRecord::Base
# note: there is also a :description attribute!!
attr_protected :file_name, :content_type, :binary_data
def image_file=(input_data)
self.file_name input_data.original_filename
self.content_type = input_data.content_type.chomp
self.binary_data = input_data.read
end
end
这是我非常简单的视图:
<h1>New Photo</h1>
<%= form_for(@photo) do |f| %>
<fieldset>
<legend>Upload a Photo</legend>
<div class="control-group">
<label class="control-label">Photo</label>
<div class="controls">
<%= f.file_field :image_file %>
</div>
</div>
<div class="control-group">
<%= f.label :description, class: "control-label" %>
<div class="controls">
<%= f.text_field :description, class: "text_field" %>
</div>
</div>
<div class="form-actions">
<%= f.submit "Upload", class: "btn btn-primary" %>
<%= link_to "Cancel", photos_path, class: "btn" %>
</div>
</fieldset>
<% end %>
最后(仅出于完整性考虑),这是我的 Create 操作(简单的脚手架):
def create
@photo = Photo.new(params[:photo])
respond_to do |format|
if @photo.save
format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
format.json { render json: @photo, status: :created, location: @photo }
else
format.html { render action: "new" }
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
这个想法是用户将选择一个文件并键入一个小的描述,该描述应该发布到/photos
控制器上的“创建”方法。不幸的是,当我单击提交按钮时,我得到一个非常模糊的错误,它没有给我关于真正问题的信息:
ArgumentError in PhotosController#create
wrong number of arguments (1 for 0)
Rails.root: /Users/me/dev/photo-app
Application Trace | Framework Trace | Full Trace
app/models/photo.rb:4:in `image_file='
app/controllers/photos_controller.rb:43:in `new'
app/controllers/photos_controller.rb:43:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"qSjMHgjCDo2ORmTvnujrljfPCj6oekLI9KAz4x5gA7Q=",
"photo"=>{"image_file"=>#<ActionDispatch::Http::UploadedFile:0x00000101726fd0 @original_filename="SomePic.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"photo[image_file]\"; filename=\"SomePic.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/kc/8hsmx29j3xn2_j_9tsw8bz6w0000gn/T/RackMultipart20121001-52387-lre7zh>>,
"description"=>"my description"},
"commit"=>"Upload"}
我已经查看了 Google 和 StackOverflow,但似乎没有什么与我的(非常简单的)示例相匹配。任何帮助将不胜感激!
提前致谢!