开发者

How to define this route in route.rb?

I use ajax call in my javascript:

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

From browser's point of view, myUrl will be some thing like "/cars/customer_cars?car_id=3&customer_id=6", the car_id and customer_id values are depending on user's selection on the page. That's two variables. When this ajax request is sent, I would like it to call a controller function, so I need to configure myUrl in route.rb

(Something like

match /cars/customer_cars?car_id=?&customer_id=? , :to =>"cars#some_function". I just don't know the syntax of this configuration.

So, when the request is sent, CarsController's some_开发者_Go百科function will be called.

How to configure myUrl in route.rb???


You gan simply use:

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

the variables will be accessible through params[:car_id] and params[:customer_id].


Maybe you should consider having routes like that:

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

So that you can have links like

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

which would translate to

/customers/:customer_id/cars/:id

Then you wouldnt need to pass data in your $.getJSON, just the url, and in your controller, you can get params[:id] and params[:customer_id].

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

Maybe it doesnt answer exactly your question, but you should think about it. It's not good to have the urls in your javascript in my opinion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜