我是通过创建一个简单的映像板来学习导轨。我希望用户能够将图像上传到服务器,然后我能够为它们提供服务。
我正在使用rails-backbone和caperclip。
这是相关部分:
app/models/image.rb
class Image < ActiveRecord::Base
attr_accessible :url
attr_accessible :data
has_attached_file :data, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
app/Assets/javascripts/backbone/backbone/spemplates/images/submit.jst.ejs
<form id="new-image" name="image" data-remote="true" enctype="multipart/form-data">
<div class="field">
<label for="data"> image:</label>
<input type="file" name="data" id="data">
</div>
<div class="actions">
<input type="submit" value="Create Image" />
</div>
</form>
app/controllers/images_controller.rb
def create
@image = Image.new(params[:image])
respond_to do |format|
if @image.save
format.html { redirect_to @image, notice: 'Image was successfully created.' }
format.json { render json: @image, status: :created, location: @image }
else
format.html { render action: "new" }
format.json { render json: @image.errors, status: :unprocessable_entity }
end
end
end
我还运行了此迁移:
class AddAttachmentDataToImages < ActiveRecord::Migration
def self.up
add_attachment :images, :data
end
def self.down
remove_attachment :images, :data
end
end
尝试保存一个名为" fruits.png"的文件后,我将此输出在控制台中:
Started POST "/images" for 127.0.0.1 at 2012-10-31 00:55:07 -0700
Processing by ImagesController#create as JSON
Parameters: {"image"=>{"url"=>nil, "data"=>"C:\fakepath\fruits.png"}}
Completed 500 Internal Server Error in 2ms
Paperclip::AdapterRegistry::NoHandlerError (No handler found for "C:\fakepath\fruits.png"):
app/controllers/images_controller.rb:16:in `new'
app/controllers/images_controller.rb:16:in `create'
任何帮助将不胜感激!谢谢!
导轨的UJS不知道如何远程提交多个表单。从表单标签中删除data-remote="true"
。
如果通过AJAX发送表单,则很有可能无法正确编码,除非您知道自己使用JavaScript的Filedata API。您可以使用XHR级别2和FormData正确编码多部分表单。在可以编码它之前,必须读取使用FileData中的文件内容。