why no path names for custom routes in Rails
Asked Answered
O

1

15

In my rails app following in routes.rb

resources :users

leads to following output for 'rake routes'

 users        GET    /users(.:format)                 users#index
              POST   /users(.:format)                 users#create
 new_user     GET    /users/new(.:format)             users#new
 edit_user    GET    /users/:id/edit(.:format)        users#edit
 user         GET    /users/:id(.:format)             users#show
              PUT    /users/:id(.:format)             users#update
              DELETE /users/:id(.:format)             users#destroy

& following in routes.rb (for my custom controller 'home')

match  '/new_user'        =>          'home#new_user', via: [:get]
match  '/users/:id/edit'  =>          'home#edit_user', via: [:get]
match  '/users/:id'       =>          'home#show_user', via: [:get]
match  '/users/:id'       =>          'home#create_user', via: [:post]

leads to following output for 'rake routes'

GET    /new_user(.:format)                home#new_user
GET    /users/:id/edit(.:format)          home#edit_user
GET    /users/:id(.:format)               home#show_user
POST   /users/:id(.:format)               home#create_user

why there are no path names for second case? like in first case ('new_user', 'edit_user')

is there any way to have path names for second case? as i want to use these path names in my views

Ofelia answered 8/4, 2013 at 18:17 Comment(0)
B
43

There are no path names because you haven't specified path names. If you're supplying custom routes instead of using resources, you need to use :as to provide a pathname:

match '/new_user' => 'home#new_user', via: :get, as: :new_user

You should also just use get instead of match... via: :get:

get '/new_user' => 'home#new_user', as: :new_user

However, given your set of routes, your better bet is to continue using resources, but to supply a limited list of actions via :only and a custom controller via :controller:

resources :users, only: %w(new edit show create), controller: "home"
Bartz answered 8/4, 2013 at 18:19 Comment(3)
Thanks.. that was quick, +1 :) , one more question is there any advantage of dropping 'match... via: :get'? as you said aboveOfelia
My way is shorter and clearer. The better question is: Is there any advantage to using match... via: :get over get?Bartz
got it..i will go your wayOfelia

© 2022 - 2024 — McMap. All rights reserved.