通过updated_at对ruby数组进行排序

时间:2009-07-23 12:12:03

标签: ruby-on-rails ruby arrays model sorting

我想做的就是从我的模特中获取最新的项目 通过属性“updated_at”对数组进行排序(最新的项目)。

某处是错误,但我找不到它:

  @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}

3 个答案:

答案 0 :(得分:10)

您需要在排序中进行比较。 `

  @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}

这将对@results数组进行排序。

答案 1 :(得分:8)

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)

答案 2 :(得分:2)

也许不是简洁或可读,但它有点干。我无法说服自己这比weppos的回答更好。我喜欢用“Class.all”替换“Class.find:all”。

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