Di aplikasi Rails4 saya, saya memiliki model Produk yang memiliki banyak Gambar Produk. Saya mencoba mengunggah file jquery untuk membuat gambar dalam formulir induk dengan menggunakan file_field, dan bidang saya disetel ke unggah otomatis ketika file dipilih. Saya hanya memiliki metode membuat dan menghancurkan di pengontrol Product_images saya.
Namun, ketika mencoba memposting ke URL: "/products/1/product_images" saya mendapatkan kesalahan perutean.
No route matches [PATCH] "/products/1/product_images"
Saya melihat di konsol browser bahwa metode permintaan saya adalah "POST", tetapi aplikasi Rails mencoba mencocokkannya sebagai 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
Apa yang menyebabkan aplikasi menggunakan PATCH?
Rute.rb
resources :products do
resources :product_images, only: [:create, :destroy]
end
Bentuk sebagian untuk gambar
<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 saya
$(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,
}
});
});
Pengontrol
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