ในแอป Rails4 ของฉัน ฉันมีโมเดล ผลิตภัณฑ์ ซึ่งมี ProductImages มากมาย ฉันกำลังพยายามรับการอัปโหลดไฟล์ jquery เพื่อสร้างรูปภาพในรูปแบบพาเรนต์โดยใช้ file_field และฉันได้ตั้งค่าฟิลด์ของฉันให้อัปโหลดอัตโนมัติเมื่อเลือกไฟล์ ฉันมีเพียงวิธีการสร้างและทำลายในตัวควบคุม 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>
จาวาสคริปต์ของฉัน
$(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