9

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?

dotNETbeginner
  • 3,402
  • 8
  • 40
  • 57

3 Answers3

11

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
max
  • 76,662
  • 13
  • 84
  • 137
  • Another important thing to remember is that routes don't give a damn about your controllers or models. They just try to match the incoming request and if the controller does not really exist its not their problem. – max Sep 08 '17 at 15:17
3

Both index and show are GET method, but the difference is index is collection type and show is member type. Which means index does not expect any parameter in the url, but show expects id param in the url.

EX:
Index: /posts
Show: /posts/:id
Mohanraj
  • 3,414
  • 1
  • 19
  • 23
2

Rails chose convention over configuration. That's why the actions are not explicitly named.

Here is the complete list of the expected actions for a given controller: http://edgeguides.rubyonrails.org/routing.html#crud-verbs-and-actions

crud-verbs-and-actions

Kruupös
  • 3,788
  • 2
  • 22
  • 35