views:

660

answers:

3

Hello,

all I want to do, is to fetch the lastest item from my models and have them in an array sorted (freshest items first) by the attribute "updated_at".

Somewhere is an error, but I can't find it:

  @results = Array.new
  Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
      @results << item
  end

  Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
    @results << item
  end


  @results = @results.sort_by{ |result| result.updated_at}
+2  A: 

You need to do the comparison in the sort. `

  @results = Array.new
  Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
      @results << item
  end

  Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
    @results << item
  end
  @results.sort!{|a,b|a.updated_at <=> b.updated_at}

This will sort the @results array in place.

Rob Di Marco
Thanks for your answer!
Stefan
+5  A: 
notes    = Note.find    :all, :limit => 3, :order => "created_at DESC"
pictures = Picture.find :all, :limit => 3, :order => "created_at DESC"
@results = (notes + pictures).sort_by(&:updated_at)
Simone Carletti
Thanks for your answer!
Stefan
+2  A: 

Maybe not as terse, or readable, but it is a little DRYer. I can't convince myself this is better than weppos's answer. I do like replacing "Class.find :all" with just "Class.all".

results = [Note, Picture].inject([]) do |memo, clazz|
  memo + clazz.all(:limit => 3, :order => "created_at DESC")
end
results = results.sorted_by(&:updated_at)
BigCanOfTuna