I have a long array of Photo model objects, and I want to sort them by created_at, newest first, then get a new array with the first 21 photos.
My problem is that the final array is not ordered properly.
Here is my code:
@recent_photos = photos.sort_by(&:created_at).reverse.first(21)
when I print out @recent_photos the created_at values are ordered like this:
1458948707
1458943713
1458947042
1458945171
...
What is the correct way to sort objects?
UPDATE:
here's how the initial list is compiled:
photos = @user.photos
@following = @user.following
@following.each do |f|
photos += f.photos if f.id != @user.id
end
@user.memberships.each do |group|
photos += group.photos
end
SOLUTION:
problem was with the question - I wanted to sort by timestamp not created_at, and those were timestamp values in the output
created_at?photos.map(&:created_at).first(21)and paste it? Your sorting should definitely be in the correct order unless I'm missing something.