Custom routes in rails
-
28-05-2021 - |
Question
I have a users controller.
For a specific user I want to have something like this
example.com/a_constant_string ==> example.com/users/2
I just need for a specific user, not for all users. You can say
link_to 'Go to a specific user', @user
link_to 'Go to a specific user', user_path(@user)
link_to 'Go to a specific user', a_constant_string_path
Should be same.
Solution
You could create a redirect route in config/routes.rb:
match '/a_constant_string', :to => redirect("/users/2")
Which would redirect to the correct path, and gives you the URL and PATH helpers: a_constant_string_path
and a_constant_string_url
.
OTHER TIPS
This would work too:
match '/a_constant_string', {controller: 'users', id: 2}
with the added benefit (IMO) of not sending a browser redirect.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow