Tagging in rails from scratch part 3

2018-11-27


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
  end

  # 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)
  end
end

h


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

def tags
  @tags = Contacts.tag_collection
end


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 %>
  </li>
<% end %>


my image

Back to articles