Rails:ユーザーによる最も使用されているActs_as_taggableタグを並べ替える

StackOverflow https://stackoverflow.com/questions/3477668

  •  28-09-2019
  •  | 
  •  

質問

2つのモデルを設定しました。 userpost. 。各 post belongs_to a user. postsは、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]}

たぶんそれをするより良い方法があるでしょう。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top