Ruby on Rails ajax发布失败

时间:2016-04-14 15:49:54

标签: javascript ruby-on-rails ruby ajax

以下是我的用户发布更新的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"):谢谢!!

1 个答案:

答案 0 :(得分:0)

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

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

你不需要在数据哈希中传递attachment_id。

顺便提一下,您发布的2条路线基本上都是一样的。你可能会失败

match "update_cover", via: [:post]