[英]Ruby having trouble sorting hash within array
I have a data model that returns the following array: 我有一个返回以下数组的数据模型:
[[54993, {:posted_at=>1363066554, :item_id=>55007,..}],..]
The 54993
is the post_id. 54993
是post_id。 I'm trying to take this array and sort by posted_at
. 我正在尝试使用这个数组并按
posted_at
排序。 The array comes sorted correctly by posted_at
. 该数组由
posted_at
正确排序。 Here's my current code: 这是我目前的代码:
post_ids = UserFeed.new(current_user.id).posts.collect{|x| x[0]}
posts = Post.where(:id => post_ids)
This sorts it by post_id
, not posted_at
. 这是通过
post_id
而不是posted_at
。 I'm trying to figure out how to sort by posted_at
, and wondering why the array resorts by post_id
. 我试图找出如何按
posted_at
排序,并想知道为什么数组通过post_id
进行排序。
If you really need that array in memory instead of sorting your data using a DB query, try this: 如果您确实需要内存中的数组而不是使用数据库查询对数据进行排序,请尝试以下操作:
method_that_returns_array.sort{ |a, b| a[1][:posted_at] <=> b[1][:posted_at]}
But ordering with a query is the preferred way: 但是使用查询排序是首选方式:
Post.order(:posted_at)
Hope it helps :) 希望能帮助到你 :)
where(ids)
does not set order, it uses a SQL IN (id1, id2, ...)
. where(ids)
没有设置顺序,它使用SQL IN (id1, id2, ...)
。 With ActiveRecord: 使用ActiveRecord:
post_ids = UserFeed.new(current_user.id).posts.map(&:first)
posts = Post.where(:id => post_ids).order("posted_at ASC")
If there is no attribute posts.posted_at
, then, solution 1: 如果没有
posts.posted_at
属性,则解决方案1:
posts = post_ids.map { |post_id| Post.find(post_id) }
Solution 2: this performs a single query and then sorts: 解决方案2:执行单个查询然后排序:
indexes = Hash[post_ids.map.with_index.to_a]
posts = Post.where(:id => post_ids).sort_by { |p| indexes[p.id] }
There was a typo in the question that really changes the question, so the first thing that comes to my mind, if the post_ids are sorted correctly is: 问题中有一个错误确实改变了问题,所以我想到的第一件事是,如果post_ids正确排序,则:
posts = []
post_ids.each do |post_id|
posts << Post.find(post_id)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.