Search code examples
ruby-on-railsacts-as-taggable

Rails: Sort most used acts_as_taggable tags by a user


I have set up two models: user and post. Each post belongs_to a user. posts also have tags, using acts_as_taggable. On UserController#show I want to list the tags the user uses, sorting from most used to less used.

Getting a list of tags is not hard, but how can I sort them? I use this to find the tags:

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

Can anyone explain me how I can sort the tags? Thanks.


Solution

  • you could use tag_counts method provided by plugin:

    @user.posts.tag_counts
    

    more info here: http://agilewebdevelopment.com/plugins/acts_as_taggable_on_steroids

    EDIT:

    a basic simple code for sorting:

    @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]}
    

    maybe there's a better way of doing it.