我正在尝试检索一些通过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=2 404(未找到)

最佳答案

在此处查看Rails路由:Rails Routes

路线是从上至下读取的,因此它在第一次引用仓库时会寻找: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


请注意,自定义路线位于资源上方。

09-07 21:15