Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:via => [:options] in ruby on rails routes

In some Rails app, I saw this in the routes.rb

root :to => "home#index", :via => [:get]
root :to => "accounts#manage", :via => [:options]

I could not understand how these two root URLs can exist. Googling didn't help clear the :options argument either. Can anyone help?

Thanks

like image 432
rookieRailer Avatar asked Apr 25 '13 18:04

rookieRailer


People also ask

What is the role of the AS => Name option in the route declarations?

The :as option creates a named path. You can then call this path in your controllers and views (e.g. redirect_to things_path ). This isn't very useful for the root path (as it already named root ), but is very useful for new routes you add.

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.

How do routes work in Ruby on 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 do I list a route in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.


2 Answers

As per the HTTP spec (and explained a bit more here), there is an OPTIONS verb - which routes can support.

The impetus for using OPTIONS is to request documentation for a web service API; results are meant to provide information regarding how the API may be used.

ActionDispatch::Routing::HTTP_METHODS
=> [:get, :head, :post, :put, :delete, :options]

To get back to your question, in a typical browser GET request, the first route will be used. When an OPTIONS request is made, the second route will be used.

like image 153
PinnyM Avatar answered Sep 28 '22 16:09

PinnyM


You can use the :via option to constrain the request to one or more HTTP methods

See the rails guide on routing

:post, :get, :put, :delete, :options, :head, and :any are allowed as a value to this option.

As explained in a blog post, OPTIONS is just another HTTP verb to support CORS requests (a way to make cross domain AJAX requests).

Update found a blog post explaining :options

like image 28
tessi Avatar answered Sep 28 '22 16:09

tessi