Premium Content - Free Preview
Since each product has a URL associated with it, it can be linked to. You could manually create an HTML link to a specific product. For example, to link to a product with an ID of 3, you could enter:
<a href="/products/3">Product #3</a>
The above is too specific to be used in a general template. To link to any given
@product, one could use the following messy Ruby code:
<a href="/products/<%[email protected]%>"><%[email protected]%></a>
This code is really unclear, so you should never use it. Instead you should use the
link_to helper, which is a method Rails provides for creating clean links.
link_to lets you create links in your templates and outputs HTML links when the page is rendered.
Here's the general format for a simple link:
link_to "Text To Display", "URLofLink"
You can use this to create external links:
link_to "Google", "https://www.google.com"
This will create the following HTML link:
Which looks like this: Google
The Rails helper is useful for linking to pages within your application. For example, here's a link to the about page:
link_to "About", "/about"
Which will turn into the following HTML, a link to your about page:
Instead of specifying an actual address to link to, you can just specify the helper path:
link_to "About", about_path
This will create the same link as before, but is more adaptable to future changes in your routes. Open up /rails/info/routes and look at the first column to see all the helper paths in your app:
Each of those paths can be used in your Rails links.
Linking to Products
The link helper paths are especially useful for dynamic links, such as linking to specific products:
<%= link_to @product.name, product_path(@product.id) %>
As is common, Rails provides a shortcut for links to the show page of a resource: