简体   繁体   中英

Ruby/rails sort_by not ordering properly?

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

You can crunch it all down into a single query:

@recent_photos = Photo.where(
  user_id: @user.following_ids
).order('created_at DESC').limit(21)

You really do not want to be doing N queries for each of these as it will get slower and slower as a person has more people they're following. If they follow 10,000 people that's a ridiculous number of queries.

If you add a :through definition to your model you may even be able to query the photos directly:

 has_many :follower_photos,
   class_name: 'Photo',
   through: :followers

Whatever your constraints are, boil them down to something you can query in one shot whenever possible. If that's not practical, get it down to a predictable number of queries, never N.

尝试:

@recent_photos = Photo.order('created_at desc').first(21)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM