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?
You can call
tag_liston the objects and use that to figure out how many tags there are:The
tags & o.tag_listyields the intersection of the tags you’re looking for and the tags found, then we negate the size of the intersection to tellsort_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.