rmagnum2002
rmagnum2002

Reputation: 11421

scaffold routes do not expect to have id's

When I run rake routes in rails 5 app I see the following urls available:

edit_articles     GET    /articles/edit(.:format)    articles#edit
articles          GET    /articles(.:format)         articles#show
                  PATCH  /articles(.:format)         articles#update
                  PUT    /articles(.:format)         articles#update
                  DELETE /articles(.:format)         articles#destroy

this whay when I create a link_to a resource I need to include id param in it like:

link_to article.name, manager_articles_path(id: article.id)

instead of rails 4 way:

link_to article.name, manager_articles_path(article)

how can I make rails 5 routes to behave as rails 4 ones?

edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy

Thank you.

routes.rb

Rails.application.routes.draw do
  root 'home#index'
  resource :articles
end

Upvotes: 1

Views: 152

Answers (1)

Ajay Barot
Ajay Barot

Reputation: 1680

In rails resource and resources is not same.

resource

http://guides.rubyonrails.org/routing.html#singular-resources

Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action.

routes

 edit_articles     GET    /articles/edit(.:format)    articles#edit
 articles          GET    /articles(.:format)         articles#show
                   PATCH  /articles(.:format)         articles#update
                   PUT    /articles(.:format)         articles#update
                   DELETE /articles(.:format)         articles#destroy

resources

resources is used as a way to handle generic requests on any item, then a singular resource is a way to work on the current item at hand.

routes

articles     GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
 new_article GET    /articles/new(.:format)      articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy

I hope this will help you.

Upvotes: 4

Related Questions