DEV Community

Cover image for Replace 7 CRUD Routes on Rails with one Line of Code
Rixio Barrios
Rixio Barrios

Posted on

Replace 7 CRUD Routes on Rails with one Line of Code

Nope, this is not click bate!. It's the syntax that resolves having to type all the 7 standard routes that a CRUD Rails app contains. Here is a quick glance at the routes:

get 'cars', to: 'cars#index'
get 'cars/new', to: 'cars#new'
post 'cars', to: 'cars#create'
get 'cars/:id', to: 'cars#show'
get 'cars/:id/edit', to: 'cars#edit'
patch 'cars/:id', to: 'cars#update'
delete 'cars/:id', to: 'cars#destroy'
Enter fullscreen mode Exit fullscreen mode

Here is the keyword that contains the same standard routes:

resources :cars
Enter fullscreen mode Exit fullscreen mode

The command creates each route with prefixes. Here is the equivalent of resources :cars:

get 'cars', to: 'cars#index'
post 'cars', to: 'cars#create'
get 'cars/new', to: 'cars#new', as: :new_car
get 'cars/:id/edit', to: 'cars#edit', as: :edit_car
get 'cars/:id', to: 'cars#show', as: :car
put 'cars/:id', to: 'cars#update'
patch 'cars/:id', to: 'cars#update'
delete 'cars/:id', to: 'cars#destroy'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)