Links


Premium Content - Free Preview

Rails Links

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.

General Format
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:

<a href="https://www.google.com">Google</a>

Which looks like this: Google

Internal Links

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:

<a href="/about">About</a> 

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:


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]