在我的rails4应用中,我有一个型号产品,它有很多 ProductImages 。我试图通过使用file_field来获取jquery文件上传以在父表单中创建图像,并且我在选择文件时将我的字段设置为autoupload。我只在Product_images控制器中创建和销毁方法。
但是,当它试图发布到URL:“/ products / 1 / product_images”时,我收到路由错误。
No route matches [PATCH] "/products/1/product_images"
我在浏览器控制台中看到我的请求方法是“POST”,但rails应用程序试图将其匹配为PATCH ...
Remote Address:127.0.0.1:80
Request URL:http://appname.dev/products/1/product_images
Request Method:POST
Status Code:404 Not Found
是什么导致应用使用PATCH?
的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
答案 0 :(得分:2)
由于您尝试在产品编辑表单中创建product_image
,当JqueryFileUpload
插件向服务器发送数据时,它会发送所有表单数据。
通过form_for
方法检查生成的HTML并搜索名为method的隐藏字段。您会发现该值为patch
:
<input name="_method" type="hidden" value="patch">
Rails use this param to determine if POST is an PUT, PATCH or DELETE
你有两个选择来解决这个问题(我更喜欢第一个):
patch
路由添加到路由文件路由到product_images #create action:_method
值