繁体   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