-
Notifications
You must be signed in to change notification settings - Fork 1
05 Post Navigation
We are now able to add posts, but you may notice there's no way to get to our New Post page without typing in the URL manually. Let's fix that by adding a link to the sidebar.
Open app/views/layouts/application.html.erb
and find the word sidebar. We don't really want the word sidebar on our page. Let's replace it a link to our form.
app/views/layouts/application.html.erb
<div class="col-xs-3">
<nav id="sidebar">
<div class="well">
<a href="/posts/new">Submit a new link</a>
</div>
</nav>
</div>
Refresh the page and try out the new link. When you're finished, hit your browser's back button to return to the index.
While the link worked, you might be thinking we should use our routes just as we did in the redirect within the controller. Let's consult the documentation for ActionView::Helpers::UrlHelper
.
ActionView::Helpers::UrlHelper
actionview/lib/action_view/helpers/url_helper.rb
Provides a set of methods for making links and getting URLs that depend on the routing subsystem (see ActionDispatch::Routing). This allows you to use the same format for links in views and controllers.
Indeed, one of the big advantage of these helpers (path helpers work just like URL helpers in this regard) is that we can use the same format in views that we do in controllers. Let's replace our hardcoded path and replace it with a path helper.
app/views/layouts/application.html.erb
<nav id="sidebar">
<div class="well">
<a href="<%= new_post_path %>">Submit a new link</a>
</div>
</nav>
That's an improvement, but we can take it one step further with the link_to
helper.
In its simplest form, we just pass the link text and the path/URL to be used as the href
value.
link_to 'Submit a new link', new_post_path
When link_to
becomes most valuable is when we need to do funky stuff, like use an HTTP verb other than GET or trigger an Ajax request.
In this case, our needs are simple.
app/views/layouts/application.html.erb
<nav id="sidebar">
<div class="well">
<%= link_to 'Submit a new link', new_post_path %>
</div>
</nav>
Let's refresh the page and make sure the link still works.
Since we're focusing on link posts at the moment, let's go ahead and comment out the body
field in our form.
app/views/posts/new.html.erb
<!--
<fieldset>
<%# f.label :body %>
<%# f.text_area :body %>
</fieldset>
-->
Now, you may notice, there's no way to get back to /posts
from here. Let's edit our layout and make the header text link back to the index.
app/views/layouts/application.html.erb
<header>
<div class="well"><%= link_to 'Redly', root_path %></div>
</header>
We can now get to the two pages of our app, so let's commit our changes. Don't forget to check your git status, and maybe even git diff, to make sure you're committing what you expect.
$ git add .
$ git commit -m "Add header and sidebar navigation for posts."