views:

53

answers:

1

I'm a noob so please forgive if this is an easy question but I'm trying to create a 'Most Recently Popular' output for specific content on a rails project.

Right now the object I am pulling from has an attribute revision.background_title. I want to calculate popularity by finding the number of specific background_title's added over the past seven days then put them in order. For example if there are 4 background_title's named 'awesomecontent' then that would be above one that has 1 background_title named 'less awesome content'

This pulls all of them:

@revisions = Revision.find(:all, :order => "created_at desc")

Thanks.

+3  A: 

You can use the basic ActiveRecord find method to do this. The code would end up looking something like this:

@revisions = Revision.all(
  :select => "background_title, count(*) count",  # Return title and count
  :group => 'background_title',                   # Group by the title
  :order => '2 desc'                              # Order by the count descending
)

To see the output, you could then do something like this:

@revisions.each do |revision|
  puts "Revision #{revision.background_title} appears #{revision.count} times"
end

giving

Revision z appears 10 times
Revision a appears 3 times
Revision b appears 2 times

Another option would be to take a look at ActiveRecord::Calculations:

http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

Calculations supports a count method that also supports the group option. However, going this route will give you back a hash containing the background_title as the key and the count as the value. Personally, find the first method more useful.

jerhinesmith
Excellent. Thanks.Any suggestions on how to do this with a constraint on the time? For example, most popular in the past 7 days?Thanks again.
Sure, just add a `:conditions` option to the hash. For example: `Revision.all(:select => "text", :group => "text", :conditions => ['created_at > ?', 7.days.ago], :order => "text")`.
jerhinesmith
Thanks! One more thing. It's not letting me pull any other attributes associated with revisions - just revision.background_title and revision.count not revision.title. Is there a way to add that attribute into the group?