如何在route.rb中定义此路由?

时间:2011-02-13 17:37:23

标签: ruby-on-rails ruby-on-rails-3

我在javascript中使用ajax调用:

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

从浏览器的角度来看,myUrl将是“ / cars / customer_cars?car_id = 3& customer_id = 6 ”,car_id和{{ 1}}值取决于用户在页面上的选择。这是两个变量。当发送这个ajax请求时,我希望它调用一个控制器函数,所以我需要在 route.rb

中配置customer_id

(像

一样

myUrl。我只是不知道这个配置的语法。

因此,当发送请求时,将调用 CarsController some_function

如何在route.rb中配置match /cars/customer_cars?car_id=?&customer_id=? , :to =>"cars#some_function" ???

2 个答案:

答案 0 :(得分:3)

你只需使用:

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

可以通过params[:car_id]params[:customer_id]访问变量。

答案 1 :(得分: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中传递数据,只需要在你的控制器中,你可以得到params [:id]和params [:customer_id]。

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

也许它不能完全回答你的问题,但你应该考虑一下。在我看来,在你的javascript中使用网址并不好。

相关问题