rubyacts-as-taggable

how to find number of tag matches in acts as taggable on


I have two entries in my database

Obj1 is tagged with "hello, world, planet" Obj2 is tagged with "hello"

if I do modelName.tagged_with(["hello", "world", "planet", "earth"], :any=>true)

I want to sort the returned objects in order of highest to lowest number of tags matched. so in this case i'd like the order to be Obj1, Obj2

how can I do this? is there a way to get number of tags matched for each of the returned results?


Solution

  • You can call tag_list on the objects and use that to figure out how many tags there are:

    tags = %w{hello world planet earth}
    objs = ModelName.taggedWith(tags, :any => true)
    objs.sort_by! { |o| -(tags & o.tag_list).length }
    

    The tags & o.tag_list yields the intersection of the tags you're looking for and the tags found, then we negate the size of the intersection to tell sort_by (which sorts in ascending order) to put larger intersections at the front, negating the result is an easy way to reverse the usual sort order.