How to limit tag_cloud to the top 20 taggings_count?

58 views Asked by At

How can we limit the tag_cloud to 20 of the tags with highest count?

[1] pry(main)> Tag.find(1)
  Tag Load (0.2ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."id" = ? LIMIT 1  [["id", 1]]
=> #<Tag:0x007fcae0cf88e0 id: 1, name: "test", taggings_count: 4>
[2] pry(main)> Tag.find(4)
  Tag Load (0.1ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."id" = ? LIMIT 1  [["id", 4]]
=> #<Tag:0x007fcae0ca0ac8 id: 4, name: "test the comma", taggings_count: 0>
[3] pry(main)>
Started GET "/as

class Tag < ActiveRecord::Base
  has_many :taggings

tag.rb

scope :top_20, -> do
  limit(20) #This limits it to the 20 tags first made regardless of if those tags have since been deleted?
end

How can we remove tags from the tag_cloud with taggings_count: 0 (this may necessitate another SO question)? Bonus points if you answer it here ;)

_tags.html.erb

<% tag_cloud(@tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
  <%= link_to tag.name, tag_path(tag), :class => css_class %>
<% end %>

Please let me know if you need further explanation or code to help you help me :-]

schema

  create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"

  create_table "tags", force: true do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true
1

There are 1 answers

8
Arup Rakshit On BEST ANSWER

Here is code :

scope :top_20, -> {
  where("taggings_count != 0").order("taggings_count DESC").limit(20)
}