when does rails looks for Index method and when for show method in controller

dotNETbeginner picture dotNETbeginner · Sep 8, 2017 · Viewed 9.5k times · Source

I'm new to Rails and I have been following a tutorial.

I have been fiddling around with routes.rb and now in total confusion about when it looks for show method and when for index method if not explicitly mentioned?

Answer

max picture max · Sep 8, 2017

Routes are simply like regexes on steroids. They have priority in the order they are defined and match the request method, URI and any other constraints that you have added.

 get '/posts', to: 'posts#index'
 get '/posts/:id', to: 'posts#show'

The key difference to the routes above is that the regular expression which the path of request uri must match is different. '/posts/:id' includes a named segment which would match:

GET /posts/11
GET /posts/gobligook

But not:

GET /posts
GET /posts/1/foo
GET /posts/foo/bar

The full conventional set of CRUD verbs are:

get    '/posts',          to: 'posts#index'   # all posts
get    '/posts/new',      to: 'posts#new'     # form to create a post
post   '/posts',          to: 'posts#create'  # create a post from a form submission
get    '/posts/:id',      to: 'posts#show'    # show a single post
get    '/posts/:id/edit', to: 'posts#edit'    # form to edit a post
put    '/posts/:id',      to: 'posts#update'  # for legacy compatibility 
patch  '/posts/:id',      to: 'posts#update'  # update a post from a form submission
delete '/posts/:id',      to: 'posts#destroy' # delete a post

In Rails flavor REST the action is implicitly derived from the path and method.
Only the new and edit methods which are used to render forms actually explicitly add the action in the path - which is because they act on a collection or a member of a collection.

Note that the '/posts/new' route must be declared before get '/posts/:id' or the show route would match the request first (routes have priority in the order they are defined). This does not apply to get '/posts/:id/edit' since the pattern is different.

Of course typing out all those routes is really tedious so rails provides the resources macro that does this for you:

resources :posts