我正在尝试在我的 rails 应用程序中上传 ajax 图像。我正在使用 Paperclip 进行正常的图像上传,效果很好,但我似乎无法连接 ajax 方法。我正在使用 Rack RawUpload 和 File Uploader插件。我按照这里的一般说明进行操作,但我被困在实际将图像附加到创建时的新对象上。这是我的控制器代码:
@bottle = Bottle.new(params[:bottle])
@bottle.user_id = current_user.id
#file = params[:qqfile].is_a?(ActionDispatch::Http::UploadedFile) ? params[:qqfile] : params[:file]
is_qq = params.has_key?(:qqfile)
if is_qq
params[:bottle][:image] = params.delete(:file)
render :json => { "success" => true }
else
respond_to do |format|
if @bottle.save
format.html { redirect_to '/bottles', notice: 'Bottle was successfully created.' }
format.json { render json: @bottle, status: :created, location: @bottle }
else
format.html { render action: "new" }
format.json { render json: @bottle.errors, status: :unprocessable_entity }
end
end
end
这是查看代码:
<%= simple_form_for(@bottle, :html => { :multipart => true }) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :brand, :placeholder => 'Brand', :label => false %>
<%= f.input :region, :placeholder => 'Region', :label => false %>
<%= f.input :age, :collection => 5..35, :prompt => "Bottle Age", :label => false %>
<%= f.input :price, :placeholder => 'Price', :label => false, :as => :currency, :input_html => { :class => 'span2' } %>
<%= f.input :image_id, :as => :hidden %>
<%= f.text_area :notes, :placeholder => 'Tasting notes...', :size => "160x5" %>
</div>
</div>
<div class="span3 offset2">
Drag a file from your desktop here...
<div class="well" height="105" style="width:200px;height:300px;">
<!-- <img src="http://placehold.it/200x300" alt="" class="temp_image"> -->
<div id="file-uploader"></div>
</div>
or...
<%= f.file_field :image %>
</div>
<div class="span8 offset2">
<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to bottles_path, :class => 'btn btn-danger' do %>
Cancel
<% end %>
</div>
<% end %>
我正在像这样使用文件上传器上传:
var uploader = new qq.FileUploader({
debug: false,
/* Do not use the jQuery selector here */
element: document.getElementById("file-uploader"),
action: '/bottles',
allowedExtensions: ["jpg", "png"],
/*
* This uploads via browser memory. 1 MB example.
*/
sizeLimit: 1048576,
/* Set Article category on submit */
onSubmit: function(id, fileName) {
uploader.setParams({
authenticity_token: $("input[name='authenticity_token']").attr("value")
});
},
onComplete: function(id, fileName, responseJSON){
url = responseJSON.image.image.url;
$('.well').html('<img src="'+url+'" />');
$('input#bottle_image_id').val(responseJSON.image.id);
}
});
似乎使用 Rack 上传很好,并将 :file 参数传递给该方法,但我无法将 param[:bottle][:image] 与 param[:file] 一起分配,我得到错误:
undefined method `[]=' for nil:NilClass
任何帮助将不胜感激。
编辑:
所以我能够让 ajax 上传挂钩到回形针上传并添加适当的参数,但现在我需要在提交表单的其余部分时更新同一个对象,而不是创建新对象。如何存储由 ajax 上传创建的包含所有图像内容的对象,并在提交完整表单后更新它?
编辑2:我保存时得到的错误是
undefined method `save' for #<ActiveSupport::HashWithIndifferentAccess:0x007ff961d08e48>
我假设是因为我正在获取表单数据并尝试将其放在同一个 @bottle 对象中并且哈希不匹配。