3
我想在我的Rails應用程序中獲取ajax圖像上傳工作。我正在使用Paperclip進行正常的圖片上傳,並且工作正常,但我似乎無法獲得ajax方法。我正在使用Rack RawUpload和 File Uploader插件。我按照一般說明here,但我堅持實際上將圖像附加到創建上的新對象。這裏是我的控制器代碼:Ajax文件上傳軌+機架RawUpload +回形針
@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);
}
});
它似乎上傳使用機架罰款,它傳遞:文件參數的方法,但我不能分配參數[:瓶] [:圖像]與參數[:文件],我得到錯誤:
undefined method `[]=' for nil:NilClass
任何幫助將不勝感激。
編輯:
所以我能夠得到AJAX上傳掛接到回形針上傳並添加相應的參數,但現在我需要更新相同的對象,當我提交表單的其餘部分,而不是創建新對象。我如何存儲由ajax上傳創建的對象,其中包含所有圖像內容,並在完整表單提交後更新它?
編輯2: 保存時,我得到的錯誤是
undefined method `save' for #<ActiveSupport::HashWithIndifferentAccess:0x007ff961d08e48>
我以爲是因爲我走的形式數據,並試圖把它在同@bottle對象和散列不匹配向上。