Tom Hert
Tom Hert

Reputation: 947

Strange behaving Routes with AJAX call

I've fought with, in my case, totally quaint behaving of routes.rb. I've tried to implement Carmen gem into my rails app. I followed this tutorial. I wanted just two dependent select boxes where first one is Country and the second one is Region(in this case - subregion). I spent almost two hours finding out, why it isn't working. Finally, the solution was quite simple - just switch two lines in routes.rb. And now my question. Can me please anyone explain why, in first case, was the response from server error and why my rails app tried to send the request on show action? I really don't get it. Thank you.

Errors:

Routes.rb

resources :orders
get '/orders/subregion_options' => 'orders#subregion_options'

Server output

Started GET "/orders/subregion_options?parent_region=US" for 127.0.0.1 at 2012-08-13 23:18:35 -0700
Processing by OrdersController#show as HTML
  Parameters: {"parent_region"=>"US", "id"=>"subregion_options"}
  Order Load (1.3ms)  SELECT "orders".* FROM "orders" WHERE "orders"."id" = $1 LIMIT 1  [["id", "subregion_options"]]
Completed 500 Internal Server Error in 3ms

ActiveRecord::RecordNotFound (Couldn't find Order with id=subregion_options):
  app/controllers/orders_controller.rb:26:in `show'

Correct behavior:

Routes.rb

get '/orders/subregion_options' => 'orders#subregion_options'
resources :orders

Server output

Started GET "/orders/subregion_options?parent_region=US" for 127.0.0.1 at 2012-08-13 23:20:10 -0700
Processing by OrdersController#subregion_options as HTML
  Parameters: {"parent_region"=>"US"}
  Rendered orders/_subregion_select.html.erb (3.0ms)
Completed 200 OK in 5ms (Views: 4.6ms | ActiveRecord: 0.0ms)

Upvotes: 0

Views: 85

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

The reason is that the routes in routes.rb are defined in the order they appear. When you write resources :orders, you are implicitly creating a route that matches GET /orders/:id to the show action on your orders controller, so when you go to /orders/subregion_options rails interprets subregion_options as the id, hence the error.

In your second version, you change the order and thus /orders/subregion_options gets correctly matched to the subregion_options action before the resource route is defined. That's why the second version works and the first doesn't.

Incidentally, this is a cleaner way to define that route:

resources :orders do
  collection do
    get 'subregion_options'
  end
end

Upvotes: 1

Related Questions