문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top