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

How to limit tag_counts items when using acts_as_taggable


I'm using the "acts_as_taggable_on" gem on my podcast page.

tag_counts shows all tags, using this HAML code:

#tag_cloud
    %h3
       = raw Podcast.tag_counts.sort{ |x, y| x.name.upcase <=> y.name.upcase }.map{  |p| link_to p.name, podcasts_path(tag: p.name), remote: true}.join(' ')

I think it will display a mess as tags will continuously be created. I want to show only one row and if the tags are over the row, a button will show and visitors can click it to append them all.

Is there a way I can limit items with tag_counts in "acts_as_taggable"?


Solution

  • Just use first() in the line that sorts, maps, then joins:

    Podcast.tag_counts.sort { ... }.map { ... }.join(' ')
    

    The first part returns an Array, and Array#first will "limit" the results to 10, in this example:

    Podcast.tag_counts.sort { ... }.map { ... }.first(10).join(' ')
    

    In your code, an extremely long line is unwieldy, and you should reorganize or break it up.