Thursday, February 10, 2011

Sort ruby array by updated_at

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}
  • 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.

    Stefan : Thanks for your answer!
  • 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)
    
    Stefan : Thanks for your answer!
  • 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)
    

0 comments:

Post a Comment