From <a href> to link_to

Free preview 2 min to read

Two lines you've already seen

Lesson 1 of Links and images, on the <a> tag, showed these two lines in an ERB file without explaining them:

<%= link_to "Products", products_path %>
<%= link_to "Blue T-Shirt", product_path(@product) %>

Both render as ordinary <a href="..."> tags, the HTML that lesson covered. The tag doesn't change; what changes is who writes it. Instead of typing href="/products", link_to and a route helper build it from inside a Rails view.

Why a helper exists for something HTML already does

An <a> tag is a few keystrokes and an href. Writing it by hand looks shorter, until an app has views across dozens of files linking to the same pages. link_to exists so that every link to a destination updates together when that destination changes, which lesson 3 covers with named routes.

This course's shape

Lesson 2 opens link_to: its two required arguments and the HTML it produces. Lesson 3 connects it to the named route helpers, like partners_path and dashboard_path, from Rails routes: basics. Lessons 4 and 5 cover the options hash, class: and other HTML attributes, with lines from this project's views. Lesson 6 checks every claim live, as the recent Rails courses have. Lesson 7 shows link_to's full shape in one place and points to the next helper this project leans on: image_tag.

Lesson 1 of 7 · free

Keep going with lesson 2

link_to's two required arguments

Covers the two required arguments of link_to, text then destination, and the plain anchor tag they return.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...