RubyonRails ajax发布失败

Ruby on Rails ajax post failed

本文关键字:失败 布失败 ajax RubyonRails      更新时间:2024-07-05

以下是我的javascript,用户在其中发布更新:

$('.attachments-container').on('click', '.cover-attachment', function(event) {
                var attachment_id = $(this).parent().find('input[name="product_attachment[id][]"]').val();
                $.ajax({
                    type: "POST",
                    url: "/products/update_cover",
                    dataType: "json",
                    data: attachment_id,
                    complete: function(){
                        console.log('change completed');
                    }
                });
                event.preventDefault();
            })

在我的路线上:

resources :products do
        member do
            match "update_cover", via: [:post]
            post "update_cover" => 'products#update_cover'
        end
    end

在我的控制器上:

class ProductsController < ApplicationController
skip_before_action :authenticate_user!, only: [:result, :show]
def update_cover
        @attachment_id = params[:attachment_id]
        render :json => {:status => 'success'}.to_json
    end
end

我不知道这个错误是从哪里来的:ActionController::RoutingError (No route matches [POST] "/products/update_cover"):谢谢!!

如果您在终端中运行rake路由,您将看到您没有products/update_cover的路由。您有-products/:id/update_cover。由于您已将其定义为成员路由,因此需要将parent_id作为路由的一部分进行传递。试试这个

url: "/products/" + attachment_id + "update_cover",

并且您不需要在数据哈希中传递attachment_id。

顺便说一句,你发布的两条路线基本上都是一样的。你可能会失去

match "update_cover", via: [:post]