'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.
Solution 1:[1]
match '/users' => "users#options", via: :options
would also be a possible route if placed before the other routes.
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
If you met this problem using javascript's ajax call, you maybe meet the cross-site problem. (e.g. your browser's current url is : http://a.xx.com and the ajax send a request to http://b.xx.com ) , then Rails / other-backend-server will get this kind of OPTIONS request.
To avoid this, besides changing your ruby code, I suggest you do one of these two solutions:
add CORS support using: https://github.com/cyu/rack-cors, lines of code just work.
send all the request to
a.xx.com, then change your Nginx's config, redirect these requests tob.xx.com.
By the way, I don't suggest you change your routes.rb file to support OPTIONS request. This will mess your code up.
refer to: AXIOS request method changes to 'OPTIONS' instead of 'GET'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pensan |
| Solution 2 | William Weckl |
| Solution 3 | |
| Solution 4 | Siwei |
