92da0010f0175533c7cbe3474d95bcfc

What I'm doing is getting the latest entry (created_at) for each unique URL (there are duplicate values in the url column, but each record has a unique created_at).

RankHistory.find_by_sql('select * from rank_histories rh where created_at = (select max(created_at) from rank_histories nstd where nstd.url = rh.url)')

Refactorings

No refactoring yet !

4d72203c38dd5f3e3d2d446b5888e8a7

Elij

December 11, 2008, December 11, 2008 19:58, permalink

No rating. Login to rate!

not really sure what you mean...

RankHistory.find(:all, :conditions => [ "created_at IN (?)", RankHistory.maximum(:created_at, :group => :id)])
8bcbb472df031a382f4346e2f959bf67

Jack Danger

December 11, 2008, December 11, 2008 20:05, permalink

No rating. Login to rate!

That's a toughy. Are you trying to find all records that were created in the most recent batch? Or just the very most recent RankHistory record?

# for one record
RankHistory.find :first, :order => "created_at DESC"

# or if you wanted it cleaner you could do it in two queries

latest = RankHistory.find :first, :order => "created_at DESC"
all = RankHistory.find :all, :conditions => ["created_at = ?", latest.created_at]

# but I'm not sure of a better way to do it in one :(
A8d3f35baafdaea851914b17dae9e1fc

Adam

December 11, 2008, December 11, 2008 20:18, permalink

No rating. Login to rate!
class RankHistory < ActiveRecord::Base
  def self.last_created
    find_by_sql <<-END_SQL
      SELECT * FROM rank_histories rh WHERE created_at =
        (SELECT MAX(created_at) FROM rank_histories nstd WHERE nstd.id = rh.id)
    END_SQL
  end
end

# RankHistory.last_created
92da0010f0175533c7cbe3474d95bcfc

Teflon Ted

December 11, 2008, December 11, 2008 20:32, permalink

No rating. Login to rate!

It's even uglier, but it's at least a named scope and thus can be combined and chained with other scopes.

named_scope :latest, :conditions => 'id in (select id from rank_histories rh where created_at = (select max(created_at) from rank_histories nested where nested.url = rh.url))'

Your refactoring





Format Copy from initial code

or Cancel