我有一个带有标签的应用程序,效果很好,但我想知道是否有办法将标签云限制为仅最流行的标签?
现在看起来它正在按照创建标签的顺序对我的云进行排序,并且我的模型内的 tags_count 方法中的限制为 10。
我使用“标记”从头开始,我没有使用acts_as_taggable
.
控制器:
class DailypostsController < ApplicationController
def index
if params[:tag]
@dailyposts = Dailypost.tagged_with(params[:tag])
else
@dailyposts = Dailypost.all
end
end
end
楷模:
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
意见:
<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>
应用助手:
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