0

我设置了两个模型:userpost. 每post belongs_to一个user. posts 也有标签,使用acts_as_taggable。在UserController#show我想列出用户使用的标签,从最常用到最不常用的排序。

获取标签列表并不难,但是如何对它们进行排序?我用它来查找标签:

@tags = []
@user.posts.each do |post|
  @tags += post.tags
end

谁能解释我如何对标签进行排序?谢谢。

4

1 回答 1

0

您可以使用插件提供的 tag_counts 方法:

@user.posts.tag_counts

更多信息在这里:http ://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids

编辑:

用于排序的基本简单代码:

@tags = Hash.new(0)
@user.posts.each do |post|
  post.tags.each do |tag|
    @tags[tag] += 1 if @tags.has_key?(tag)
  end
end
# sorting
@tags.sort{|a,b| a[1] <=> b[1]}

也许有更好的方法来做到这一点。

于 2010-08-13T14:34:21.060 回答