views:

51

answers:

1

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!)

+3  A: 

Assuming the following setup:

class Item < ActiveRecord::Base
  has_and_belongs_to_many :tags
end

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :items
end

You should be able to do:

@tag = Tag.find(PARAMS)
@tag.items.find(:all, :order => "items.score DESC", :limit => 10)

If you want to make it even slicker, add this line to your Item class:

named_scope :popular, :order => "items.score DESC", :limit => 10

You can then call

@tag.items.popular
Peter Wagenet
Just what I was looking for - thanks. Good to see it's that simple.