abcd_win
abcd_win

Reputation: 107

Rails default routes through resources implementation

resources :photos

Creates seven different routes, all mapping to the Photos controller.

GET /photos

GET /photos/new

POST /photos

GET /photos/:id

GET /photos/:id/edit

PATCH/PUT /photos/:id

DELETE /photos/:id

But where is it defined in the rails application, from where it is picked automatically.

If we need to implement some routes the same way resources does, how can we do it?

Upvotes: 2

Views: 1106

Answers (2)

Wally Ali
Wally Ali

Reputation: 2508

To answer this question: If we need to implement some routes the same way resources does, how can we do it?:

From resources :photos, the following is how you can create individual routes:

get 'photos', to: 'photos#index'
post 'photos', to: 'photos#create'
get 'photos/new', to: 'photos#new'
get 'photos/:id/edit', to: 'photos#edit'
get 'photos/:id', to: 'photos#show'
patch 'photos/:id', to: 'photos#update'
put 'photos/:id', to: 'photos#update'
delete 'photos/:id', to: 'photos#destroy'

It's as simple as that. if you don't want all the routes that comes with resources, you can simply implement the ones you need.

Upvotes: 2

brikkoroller
brikkoroller

Reputation: 16

When you use

resource :photos

rails generates automatically the CRUD routes that allow you to Create, Read, Update and Destroy photos. Rails uses here a number of conventions for mapping those basic CRUD routes to the controller actions. For example, POST methods are associated to create() actions of your controllers.

This behavior is implemented in the module ActionDispatch::Routing::Mapper::Resources.

If you need to add a new route (for a new controller action) which is not part of the conventional CRUD set of actions, you need to specify it in the routes.rb file of your rails application.

You have two options:

a. The action affects a collection of Photo objects (similar to the index action). For this you need to add the route within the 'collection' block. This translates into a route without any :id parameter in the URL of the route.

resources :photos collection do get 'thumbnail' end end

b. The action affect only Photo object (similar to edit and destroy actions). For this you need to add the route within the 'member' block and will make you available the :id param in the controller. The resulting URL of the route will need to specify the it in /photos/:id/my_action

resources :photos member do get 'gallery' end end

Please also have a look at http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

Upvotes: 0

Related Questions