How do I add a new route (URL)? Question
I was thinking about taking a try at an issue that would add a new sub-page to the user profile. I understand that as part of this I need to add a "route" for the new URL and somehow wire that up to the view that I will define.
I'm new to that part of Ruby; so far I have only modified existing views, not created new ones. How does that work?
1 answer
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
Monica Cellio | (no comment) | Sep 15, 2024 at 16:12 |
You can add a new route in the file config/routes.rb
, and the existing routes in that file for the other "tabs" on the user profile page show the template to follow.
The relevant part of the routes file starts on line 180:
scope 'users' do
Everything inside this scope
block effectively has users
prepended to its URL. For example, line 186 has:
get '/me', to: 'users#me', as: :users_me
This lists the URL as /me
but is actually triggered by the URL users/me
due to being inside the users
scope block.
Similarly line 200 has:
get '/:id', to: 'users#show', as: :user
This is triggered by the URL users/:id
(such as users/1234
).
The other tabs on the user profile page have URLs of the form users/:id/something
and can be found in this block listed as just /:id/something
(or /me/somethng
for the ones not visible to the public other than the user).
What the components mean
GET
The get
at the beginning of the line means that this is triggered by a GET request (often used for visiting the page rather than making a background server request).
URL
The URL reflects what link the user followed, subject to having the scope (in this case users
) prepended.
To
The to: 'users#show'
is interpreted in both of two ways:
- This URL results in a call to the
show
method of theUsersController
. - The view rendered is the file
show.html.erb
in the directoryusers
.
As
The as: :user
is an optional renaming of the helper functions that Rails automatically creates for each route.
By default, the methods users_show_path
and users_show_url
would be created (matching users#show
). The as
overrides this to have the methods be called user_path
and user_url
instead.
1 comment thread