I have a database with two tables: tags and items.
Each Item has a score, the highest scoring items being the most popular. There is a many-to-many relationship between tags and items.
Getting all items belonging to a tag is easy. (= tag.items
) But how do I retrieve the 10 most popular items belonging to this tag?
So in fact I need the ruby equivalent of
SELECT * from items INNER JOIN item_tags ON items.id = item_tags.item WHERE item_tags.tag = :tagid ORDER BY items.score DESC LIMIT 10
Since a tag might have a lot of items, I prefer to let the database do this work instead of retrieving all items and then filtering them manually. (and if there is a faster way to perform this operation, it is certainly welcome!)