问题
I have an app with Tags and it works great, but I was wondering if there was a way to restrict the tag cloud to only the MOST POPULAR tags?
Right now it looks like it's ordering my cloud by the order in which the tags were created and I have a limit of ten in in my tags_count method inside my MODEL.
I used "Tagging" to do it from scratch, and I am not using acts_as_taggable
.
Controllers:
class DailypostsController < ApplicationController
def index
if params[:tag]
@dailyposts = Dailypost.tagged_with(params[:tag])
else
@dailyposts = Dailypost.all
end
end
end
Models:
class Dailypost < ActiveRecord::Base
attr_accessible :title, :content
has_many :taggings
has_many :tags, through: :taggings
def self.tagged_with(name)
Tag.find_by_name!(name).dailyposts
end
def self.tag_counts ##Added a limit here
Tag.select("tags.id, tags.name,count(taggings.tag_id) as count").
joins(:taggings).group("taggings.tag_id, tags.id, tags.name").limit(10)
end
def tag_list
tags.map(&:name).join(", ")
end
def tag_list=(names)
self.tags = names.split(",").map do |n|
Tag.where(name: n.strip).first_or_create!
end
end
end
class Tagging < ActiveRecord::Base
attr_accessible :dailypost_id, :tag_id
belongs_to :tag
belongs_to :dailypost
# attr_accessible :title, :body
end
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :taggings
has_many :dailyposts, through: :taggings
end
Views:
<div id="tag_cloud">
<% tag_cloud Dailypost.tag_counts, %w[s m l] do |tag, css_class| %> ###Change is here
<%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>
</div>
Application helper:
def tag_cloud(tags, classes)
max = 0
tags.each do |t|
if t.count.to_i > max
max = t.count.to_i
end
end
tags.each do |tag|
index = tag.count.to_f / max * (classes.size - 1)
yield(tag, classes[index.round])
end
end
来源:https://stackoverflow.com/questions/19371294/how-do-i-show-the-top-ten-tags