[英]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. 我有很长的Photo
模型对象数组,我想按created_at
对其进行排序(最新的),然后使用前21张照片得到一个新的数组。
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: 当我打印出@recent_photos
, created_at
值的排序如下:
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 问题出在问题上-我想按timestamp
排序而不是created_at
,而这些是输出中的timestamp
值
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. 您确实不希望对每个查询都进行N次查询,因为随着一个人有更多的关注对象,查询将会越来越慢。 If they follow 10,000 people that's a ridiculous number of queries. 如果他们关注10,000人,那么查询的数量就非常可笑。
If you add a :through
definition to your model you may even be able to query the photos directly: 如果在模型中添加:through
定义,您甚至可以直接查询照片:
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. 如果这不切实际,则将其降至可预测的查询数量,而不是N。
尝试:
@recent_photos = Photo.order('created_at desc').first(21)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.