Show one chirp
URI Pattern | Controller#Action | What should it do? | Example action code |
---|---|---|---|
/chirps/:id(.:format) | chirps#show | Show an existing chirp | Chirp.find(id) |
In the show
action/function in app/controllers/chirps_controller.rb
, let's add:
@chirp = Chirp.find(params[:id])
In the corresponding view --app/views/chirps/show.html.erb
, put this in:
<h1>Chirp</h1>
<p><%= @chirp.body %></p>
<p>
- <i><%= @chirp.author %></i>
</p>
Now if we go to http://localhost:3000/chirps/2, we should see one Chirp.
Where does the value for
params[:id]
come from in ourapp/controllers/chirps_controller.rb
?
It would be nice to able to see an individual Chirp by clicking on a link from the list of all Chirps. Let's go back to app/views/chirps/index.html.erb
and add:
<%= link_to "Read more", chirp_path(chirp) %>
right before the <% end -%>
of the loop so that app/views/chirps/index.html.erb
looks like this:
Going to http://localhost:3000/chirps now should show all the Chirps, each with a link to "Read More" underneath. Clicking on each link will bring us to a new page with the specific Chirp.
We can also add a link back to the list of all Chirps in view
in each of the posts.
In app/views/chirps/show.html.erb
, add to the bottom:
<%= link_to "See All Chirps", chirps_path %>
What does link_to do for us? Discuss with the coach and look at the HTML in the browser with Inspect Element.