Linking to Pages

Users can view a list of all our page titles, but they can't view the content of single Pages yet. For our Posts resource, they can click a link on the list of all Posts to view an individual post. Let's set up links to view single Pages as well.

Let's say we need to set up links to view individual Page objects. In the URL path, following /pages/, we need a string representing the ID of the Page object we want to load. We'll set up the route like this:

get '/pages/:id', to: 'pages#show'

The colon followed by a name is a URL parameter. A URL parameter captures part of the request path, and makes it available within the controller in the params hash. So if we type :id here, it will be available later as params[:id]. We can name the parameter whatever we want, but by convention the name :id is used for model record IDs.

0:00

[MUSIC]

0:05

Users can view a list of
all our page titles but

0:07

they can't view the content
of single pages yet.

0:10

For a post resource they can click
a link on the list of all posts to view

0:13

an individual post.

0:15

Let's set up links to view
single pages as well.

0:19

We wanna turn these page titles into
links, so we can click on them and

0:23

view the associated page.

0:25

Remember how we showed you that all
saved rails model objects have an ID

0:28

attribute that's used to look
them up in the database.

0:32

Creating links is one major
reason that ID attribute exists.

0:36

We're going to use that ID in our links to
tell rails which model objects to load.

0:40

We can embed dynamic HTML links into
the output with output embedding tags.

0:49

Within rails views, a helper
method named Link to is available.

0:53

It returns the necessary HTML string for
creating a link.

0:57

Link to his first argument should be
the link text that you wanna displayed.

1:01

And the second argument should be the path
that you want the browser to request.

1:09

If we save this we'll have web links
in our output, let's say link text and

1:14

that point to the nonexistent
path of slash link, slash path.

1:19

We can see the HTML output in
our browser's developer tools.

1:24

There's the link text
within the anchor tag and

1:26

there's the path of the link references.

1:30

Now let's update this call to link two and
make it do something useful.