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}
From stackoverflow
Stefan
-
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!From Rob Di Marco -
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!From Simone Carletti -
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)
From BigCanOfTuna
0 comments:
Post a Comment