Skip to Content
Learn
Associations I
Show a tag

Well done! The app now displays a list of tags from the database.

Instructions

1.

Let’s add another action to display a specific tag. Looking at the seven standard controller actions, we need to use the show action. Let’s set it up now.

First in the routes file, add this route:

get '/tags/:id' => 'tags#show', as: :tag

Here we use as: to name this route “tag”.

2.

Then in the Tags controller, add the show action:

def show @tag = Tag.find(params[:id]) @destinations = @tag.destinations end
3.

In app/views/tags/show.html.erb inside the <h2> element, display a tag’s title.

Then in <div class="cards">...</div>, iterate through each destination in the @destinations array and display its image, name, and description.

4.

Finally in app/views/tags/index.html.erb within the <% @tags.each do |t| %>...<% end %> block, add this link:

<%= link_to "Learn more", tag_path(t) %>

By giving the route in step 1 the name “tag”, Rails automatically creates a helper method named tag_path. We use tag_path(t) here to generate the URL to a specific tag’s path, for example /tag/1.

5.

Visit http://localhost:8000/tags in the browser. Click on a ‘Learn more’ to see all destinations under that tag.

Folder Icon

Sign up to start coding

Already have an account?