簡體   English   中英

(Ruby-On-Rails4)從Ajax調用方法時發生路由錯誤

[英](Ruby-On-Rails4) Route error when calling method from ajax

我正在嘗試檢索一些通過ajax調用方法的信息。 似乎我的代碼中缺少某些內容,因為從chrome檢查進行故障排除時,出現“找不到網址”錯誤。 我的模型是倉庫和產品。 我要完成的工作是從select_tag字段中選擇一種產品時,使用該產品的默認價格填充text_field。 這是我到目前為止的內容:1. select_tag視圖:

<%= select_tag "product_selection", options_from_collection_for_select(Product.all, "id", "name") %>

2. Warehouses.js

    $(document).on("change", '#product_selection', function() {
    $.ajax({
       url: "/warehouses/get_price",
      type: "GET",
  dataType: "json",
      data: { product_id: $('#product_selection option:selected').value() }, // This goes to Controller in params hash, i.e. params[:file_name]
  complete: function() {},

   success: function(data, textStatus, xhr) {
              // Do something with the response here
              document.getElementById("default_price").value = data.default_price;                                                            
            },
     error: function() {
              alert("Ajax error!")
            }
  });
});

3. Warehouses_controller.rb

def get_price
  @price = Product.find(params[:product_id]).price
    if request.xhr?          
      render :json => { :default_price => @price }
    end
end

4. route.rb

  resources :products
  resources :warehouses

  resources :warehouses do
    member do
      get 'get_price'
    end

我從Chrome Inspect收到的消息是:

jquery.self-c64a743 .... js?body = 1:10244 GET http:// localhost:3000 / warehouses / get_price?product_id = 2404(未找到)

在此處查看Rails的路由: Rails的路由

路線是從上至下讀取的,因此它在第一次引用倉庫時會尋找:get_price。 一種選擇是合並路線:

 resources :products
 resources :warehouses do 
      member do
           get 'get price'
      end
 end

這實際上將指向

 /warehouses/{:id}/get_price

要丟失寧靜的ID,您可以嘗試

 resources :products
 resources :warehouses do 
      collection do
           get 'get price'
      end
 end

那應該回應

/warehouses/get_price

然后傳遞適當的參數。

另外,要獲取所需的路線,您可以

 get 'warehouses/get_price', to: 'warehouses#get_price'
 resources :products
 resources :warehouses

請注意,自定義路線位於資源上方。

對方法(URL:“ warehoueses / get_price”)的Ajax調用失敗,因為我在Warehouses_controller.rb的私有方法部分中生成了get_price方法,因此這基本上是我的錯誤。 無論如何,謝謝您的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM