Reputation: 919
I'm using act-as-taggable gem and want to sort similar article to a given article based on maximum similar tags, for example i have an article that i must show their related articles and is tagged with
([“awesome”, “cool”, "foo", "bar", "rails"])
and anothers tagged with
A1= ([“awesome”, “cool”, "foo", "bar", "rails"])
A2= ([“awesome”, “cool”, "foo", "bar", "python"])
A3= ([“awesome”, “cool”, "foo", "python", "django"])
in the sorting of related article A1 must be the first followed by A2 & finally A3 Howa can I achieve this
actually what i'm doing is @related_articles = Article.tagged_with(@article.tag_list, any: true)
but this show all tags with only one similar tags so even if there is some articles with 5 or 4 similar tags they will not be first, the other solution is to use :match_all => true
but if there is no article with all this tag the related article will be nil, So I'm wondering on how can i achieve this?
Upvotes: 1
Views: 141
Reputation: 23713
I am not familiar with this gem, but you could do it this way. Assuming the main article you want to get similar articles from is named @article
and its tags are accessible via @article.tag_list
, you could do:
1 - Get all the articles that match any of the tags from @article
:
@related_articles = Article.tagged_with(@article.tag_list, any: true)
2 - Sort them afterwards by doing:
@related_articles.sort_by { |ra| (ra.tag_list & @article.tag_list).size }.reverse
The key here is the &
operator. Play with it on the console :)
Upvotes: 1