Search code examples
ruby-on-railshyperlinkhref

Rails 4: Any way to fix/use regular html href links w/o 'link_to'?


So my question is that I have a link to 'pages/home' and I click on it, ill go to my home page.

But then I'll try to click again, but the link changes to 'pages/pages/home' and then I'll get a routing error. Is there anyway to fix this using regular old anchor tags? or do i need to use link_to?

edit: This is how i insert my link into the page.

<a href="pages/home">Home</a>

Solution

  • This is not related to rails, the problem is you use a relative url :

    <a href="pages/home">Home</a>
    

    This will lead to <any_path_you're_in>/pages/home.

    For it to be absolute, you have to use (note the leading slash):

    <a href="/pages/home">Home</a>
    

    By the way, it's quite a bad practice to use hardcoded url to your own rails app. You can avoid using #link_to while still taking advantage of rails' routing :

    <a href="<%= home_path %>">Home</a>
    

    Provided you have a "home" route, of course :

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

    This will save you a lot of pain when you decide to restructure your app.