Ruby On Rails中如何将a标签及图片的href替换为root_path?
<a> and Image Links to Point to root_path in Rails/Bootstrap Hey there! I’ve run into this exact scenario a bunch of times when building Rails apps with Bootstrap—let’s get your links pointing to root_path properly. Here are the most common solutions depending on your setup:
1. Updating Regular <a> Tags
Rails gives us the handy link_to helper that’s way better than hardcoding URLs (it’ll automatically adjust if your root route ever changes).
If you’re using ERB, replace your plain HTML <a> tag with:
<%= link_to "Home", root_path, class: "btn btn-primary" %>
The class attribute here is where you’ll drop your Bootstrap classes (like btn, nav-link, etc.) to keep the styling intact.
If you absolutely need to stick with plain HTML (not recommended, but sometimes necessary), you can embed the root_path helper directly in the href:
<a href="<%= root_path %>" class="nav-link">Home</a>
2. Making Images Link to root_path
To turn a logo or image into a clickable link back to your homepage, nest the Rails image_tag inside a link_to block:
<%= link_to root_path do %> <%= image_tag "your-logo.png", alt: "Site Logo", class: "img-fluid" %> <% end %>
This keeps your image styled with Bootstrap’s img-fluid class while wrapping it in a link to the root.
If you prefer plain HTML for the image, wrap it in an <a> tag with the embedded root_path:
<a href="<%= root_path %>"> <img src="<%= image_path("your-logo.png") %>" alt="Site Logo" class="img-fluid"> </a>
3. Handling Bootstrap Components (Like Navbars)
Bootstrap navbars work seamlessly with Rails helpers. For example, here’s how to set up a navbar brand logo and home link pointing to root_path:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <!-- Navbar Brand (Logo Link) --> <%= link_to root_path, class: "navbar-brand" do %> <%= image_tag "logo.svg", alt: "Brand Logo" %> <% end %> <!-- Navbar Links --> <div class="collapse navbar-collapse"> <ul class="navbar-nav me-auto"> <li class="nav-item"> <%= link_to "Home", root_path, class: "nav-link active" %> </li> <!-- Add other nav items here --> </ul> </div> </div> </nav>
Quick Check
Before testing, double-check your config/routes.rb has a root route defined, like:
root "home#index"
Without this, root_path will throw an error—Rails needs to know what controller/action maps to your homepage!
内容的提问来源于stack exchange,提问作者meister

