Articles by Sergio Xalambrí

How shallow: true works in Rails

If you have nested resources in your routes of Rails, you can use shallow: true this way

resources :articles, shallow: true do
  resources :comments
end

This will create the following URLs:

GET     /articles
POST    /articles
GET     /articles/:id
PUT     /articles/:id
DELETE  /articles/:id
GET     /articles/:article_id/comments
POST    /articles/:article_id/comments
GET     /comments/:id
PUT     /comments/:id
DELETE  /comments/:id

This way, list and create comments are nested inside the parent resource article so you don't need to pass the article_id manually because it's in the URLs, but you can still get an individual comment, update it or delete it directly with /comments/:id.