如何显示前十个标签?

时间:2013-10-15 00:12:24

标签: ruby-on-rails ruby tags acts-as-taggable

我有一个带有标签的应用程序并且效果很好,但我想知道是否有办法将标签云限制为只有MOST POPULAR标签?

现在看起来它按照创建标签的顺序对我的云进行排序,并且我的MODEL中的tags_count方法中有一个限制为10。

我使用“Tagging”从头开始,我没有使用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

0 个答案:

没有答案