在我的rails4應用中,我有一個模型產品其中有很多ProductImages。我想通過使用file_field來獲取jquery文件上傳來在父窗體中創建圖像,並且當選擇文件時,我的字段設置爲autoupload。我只在我的Product_images控制器中創建和銷燬方法。jquery-file-upload POST和嵌套路由 - 沒有路由匹配PATCH
但是,當它試圖發佈到URL:「/產品/ 1/product_images」我得到一個路由錯誤。
No route matches [PATCH] "/products/1/product_images"
我看到在瀏覽器控制檯,我的要求的方法是「POST」,但Rails應用程序試圖與之相匹配的補丁......
Remote Address:127.0.0.1:80
Request URL:http://appname.dev/products/1/product_images
Request Method:POST
Status Code:404 Not Found
是什麼原因造成該應用使用補丁?
的routes.rb
resources :products do
resources :product_images, only: [:create, :destroy]
end
表部分的圖像
<fieldset id="product-images">
<%= file_field_tag "product_images[]", type: :file, id:"file-select", multiple:true %>
<% f.fields_for :product_images do |builder| %>
<%= render "product_images/product_image", f:builder %>
<% end %>
</fieldset>
我的JavaScript
$(function(){
/* ---IMAGE AREA--- BEGIN */
//JQ FILE UPLOAD FUNCTION
var formURL = $(".edit_product").attr("action") + "/product_images";
$('#file-select').fileupload({
url:formURL,
type:'POST',
dataType: 'script',
add: function (e, data) {
data.context = $('<div class="img uploading"/>').appendTo("#product-images");
data.submit();
},
done: function (e, data) {
console.log(data.result);
$.each(data.result.files, function (index, file) {
console.log(file);
});
//$(".no_images").addClass("hidden");
},
option: {
autoUpload: true,
}
});
});
控制器
class ProductImagesController < ApplicationController
before_action :set_product_image, only: [:show, :destroy]
def show
end
def create
@product = Product.find(params[:product_id])
@product_image = @product.product_images.create(product_image_params)
if @product_image.save
respond_to do |format|
format.js
end
else
render :json => [{:error => "custom_failure"}], :status => 304
end
end
def destroy
@product_image.destroy
render :json => true
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product_image
@product_image = ProductImage.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_image_params
params.require(:product_image).permit(:product_id, :file, :title, :caption)
end
end
我接近這個錯誤的方式嗎?使用jquery-file-upload,我只想將相關的ProductImage添加到產品中,並且在添加ProductImage時不需要更新產品記錄。它看起來像發送所有我不需要的產品表單數據。過去我在頁面中爲關聯記錄創建了一個單獨的表單,並在此表單中隱藏了一個product_id字段以實現關聯,但我希望將file_field保留在父表單上。 – 2014-10-29 16:58:33
不,jquery-file-upload的默認值是發送所有表單數據。如果要編輯發送給服務器的數據,請使用[formData](https:// github。com/blueimp/jQuery-File-Upload/wiki/Options#formdata)函數。 – Rodrigo 2014-10-29 17:30:50
據我所知,我可以覆蓋使用formData ...但我應該只使用一個獨立的product_images獨立的形式,而不是使用嵌套的產品形式來創建新的圖像?這就是我在過去的項目中做過的事情 – 2014-10-29 19:42:30