lundi 7 juillet 2014

ROR: How to sort array with .limit method


Vote count:

0




I want to show the records based on created date DESC.But I have to select only one record for each user based on created date DESC. For that I am using the .limit method to get only one record from database and .order method to sort the array like this:



@messages = Message.where('FromUserId = ? or ToUserId = ?', user.id, user.id).order('created_at DESC').limit(1)
array = Array.new
@messages.each do |message|
response = Hash.new
response[:id]=message.id
response[:from]=message.FromUserId
response[:to]=message.ToUserId
response[:date]=message.created_at.strftime("%d/%m/%y %I:%M %p")
response[:content]=message.MessageContent
array.push(response)
end


But it is showing the old record on the top when I loop the array I also tried using this one:



@messges = array.sort { |a,b| a[:date] <=> b[:date] }


But again I get the same result.Can someone tell me what is the right way to do it.



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire