2011-02-13 76 views
1

我使用Ajax調用在我的javascript:如何在route.rb中定義此路線?

var myUrl = "/cars/customer_cars"  
$.getJSON(
     myUrl, 
     {car_id: car_id, customer_id: customer_id}, 
     function(data) { 
      //Deal with response data 
     } 
); 

但從瀏覽器的角度來看,myUrl會像 「/汽車/ customer_cars car_id = 3 & CUSTOMER_ID = 6?」 一些東西,car_idcustomer_id值取決於用戶在頁面上的選擇。這是兩個變量。當發送這個Ajax請求,我想它來調用一個控制器功能,所以我需要在配置myUrl route.rb

(喜歡的東西

match /cars/customer_cars?car_id=?&customer_id=? , :to =>"cars#some_function"。我只是不知道語法這個配置。

所以,當請求被髮送,CarsControllersome_function將被調用。

如何在route.rb中配置myUrl

回答

3

你甘簡單地使用:

get "/cars/customer_cars" => "CarsController#some_function" 

變量將訪問通過params[:car_id]params[:customer_id]

2

也許你應該考慮這樣的路線:

resources :customers do 
    resources :cars do 
    member do 
     get :some_function 
    end 
    end 
end 

所以,你可以有一個像

link_to "customer car", some_function_customer_car_path(customer, car) 

鏈接這將轉化爲

/customers/:customer_id/cars/:id 

然後你不會需要在你的$ .getJSON中傳遞數據,只需要url,在你的控制器中,你可以得到params [:id]和param S [:CUSTOMER_ID]。

$("a").click(function(e) { 
    $.getJSON(
     $(this).attr("href"), 
     {}, 
     function(data) { 
     //Deal with response data 
     } 
    ); 
    e.preventDefault(); 
}) 

也許它沒有回答你的問題,但你應該考慮一下。在我看來,在你的javascript中擁有這些網址並不好。

+0

好的建議,謝謝:) – Mellon 2011-02-14 07:29:28