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 !
Elij
December 11, 2008, December 11, 2008 19:58, permalink
not really sure what you mean...
RankHistory.find(:all, :conditions => [ "created_at IN (?)", RankHistory.maximum(:created_at, :group => :id)])
Jack Danger
December 11, 2008, December 11, 2008 20:05, permalink
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 :(
Adam
December 11, 2008, December 11, 2008 20:18, permalink
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
Teflon Ted
December 11, 2008, December 11, 2008 20:32, permalink
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))'
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).