Tagging in rails from scratch part 2

2018-11-25


In the first writeup of building tags from scratch, I showed how I was able to construct the tagging parts of my form. Calling tags in the view is just a matter of iterating.

@contact.tags.each do |t|
  <%= t %>
end


Now that I have tags displayed for each contact, I want to be able to click a tag and have it direct me to a new page. This new page will show me a collection of contacts that share the same tag.


First thing i'll do is i'll head over to routes to create a page. I'll also pass a slug which will be the name of the tag:

get 'search/:tag' => "pages#searchtags", as: "searchtags"


Back on the view, I'll add my rails link_to helper which passes the tag as a parameter

<% @contact.tags.each do |t| %>
  <%= link_to searchtags_path(tag: t)  do %>
    <%= t %>
  <% end %>
<% end %>


In my pages controller, i'll create two instance variables one which will allow me to grab the tag passed via the link, and the second which will allow me grab all the contacts that share the tag:

def searchtags
  @tag = params[:tag]
  @contacts = Contact.all.select{|x| x.tags.include?(params[:tag])}
end


Below is what it looks like. For the last part of this series, I'll show you how I index my tags.


my image

Back to articles