Rails:ユーザーによる最も使用されているActs_as_taggableタグを並べ替える
-
28-09-2019 - |
質問
2つのモデルを設定しました。 user
と post
. 。各 post
belongs_to
a user
. post
sは、acts_as_taggableを使用してタグもあります。の上 UserController#show
ユーザーが使用するタグをリストし、使用されていないほとんどが使用されていないほとんどのタグをリストしたいと思います。
タグのリストを取得するのは難しくありませんが、どうすればソートできますか?これを使用してタグを見つけます。
@tags = []
@user.posts.each do |post|
@tags += post.tags
end
タグを整理する方法を誰かが私に説明できますか?ありがとう。
解決
プラグインによって提供される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]}
たぶんそれをするより良い方法があるでしょう。
所属していません StackOverflow