Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you route [OPTIONS] in Rails?

I am making a REST service in Rails. Here are my routes.

  resources :users
  match '/users', :controller => 'users', :action => 'options', :constraints => {:method => 'OPTIONS'}

I am able to [GET] my users. I am trying to update my users and I get an error:

ActionController::RoutingError (No route matches [OPTIONS] "/users/1"):

When I run rake routes here are the routes that I am given:

    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
     user GET    /users/:id(.:format)      users#show
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy
                 /users(.:format)          users#options {:method=>"OPTIONS"}

Could someone please show me how to fix my routes so I can make any kind of REST call? Thanks.

like image 388
jhamm Avatar asked Jan 26 '13 18:01

jhamm


People also ask

How do routes work in Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.


3 Answers

match '/users' => "users#options", via: :options

would also be a possible route if placed before the other routes.

like image 53
pensan Avatar answered Oct 19 '22 02:10

pensan


If you don't want to create two additional routes for /users and for /users/id you can do this:

match 'users(/:id)' => 'users#options', via: [:options]

In this case, the id become optional, both /users and /users/id will respond to the same route.

like image 43
William Weckl Avatar answered Oct 19 '22 03:10

William Weckl


The reason that I could not route the request, was that my match did not have the user id in it. I added the line:

match '/users/:id', :controller => 'users', :action => 'options', :constraints => {:method => 'OPTIONS'}

and now I can route all of my GET request.

like image 40
jhamm Avatar answered Oct 19 '22 04:10

jhamm