I’ve got an app where the links work fine when I’m on the homepage, but when I’m on a page belonging to a resource such as “users”, some links get a little weird.
When I’m on the homepage and I click the link for the “About” page, I’m taken there directly. But if I’m on the page for users/index and I hover over the link for the “About” page, it shows the destination as being “users/about.”
Here’s what my routes file looks like.
RobotimusApp::Application.routes.draw do
resources :users
root to: "pages#home"
match '/about', to:'pages#about'
match '/guides', to:'pages#guides'
end
Here’s what my nav bar looks like
%ul.nav
%li
=link_to 'Home', root_url
%li
=link_to 'About', 'about'
- if user_signed_in?
%li
= link_to('My Sites', user_path(current_user))
Welp, the issue lies in this line:
Instead of passing in a routed path like
about_path, we pass in the string'about'. Whenlink_toreceives a string as its URL parameter, it doesn’t run it through the router or anything; it assumes that that’s the URL you want to go to. (After all,about_pathand the like return strings.)So, you end up with something like this in the HTML:
Here,
aboutis a relative URL, so from the path/usersit will go to/users/about.You could just use a preceding slash to make it an absolute path:
But it’s not particularly Rails-y to hard-code our URLs when we can use routes instead. You’re probably going for something like this:
(Is
about_pagesthe route name? It probably should be. You can always name it with anasparameter.)