Jason Chee

Tagging in rails from scratch part 3


In the last part of this series, I'm going to create an index page of all the tags that exist on my database.

First thing is I want to create a new route

get 'tags' => "pages#tags", as: "tags"

Because many contacts share the same tags, it would be unecessary for me to repeat a tag. Instead it would be ideal to have a tag like the example below.

In order for me to execute this, I'll create a new method in the Contacts model.

def self.tag_collection
  # Here I am grabbing all of the tags and shoving them into the empty array.
  # That empty array would look something like [["web developer"],["foodie"],["traveler"]]
  arr = []
  Contact.all.select{|x| !x.tags.empty?}.each do |c|
    arr << c.tags

  # Next I create an empty hash.
  # In the iteration below, I will flatten my array of tags, which would be passed into a hash as a key.
  # If the tag is repeated in the hash the count value will +1, if not, the count will just =1.

  h = {}
  arr.flatten.each do |x|
    h.keys.include?(x) ? (h[x] += 1) : (h[x] = 1)


Next i'll head over to the pages controller, so I can put to use this new method.

def tags
  @tags = Contacts.tag_collection

Last is just calling it in the view.

<% @tags.sort.each do |t,n| %>
  <li class="relative">
  <%= link_to searchtags_path(tag: t), class: "no-underline" do %>
    <div class="button"><%= t %></div>
    <span class="absolute"><%= n %></span>
  <% end %>
<% end %>

my image

Thanks for reading. Please feel free to contact me if you need to get in touch, or would like share your after thoughts.

⟵ Back to articles