2013-03-12 85 views
1

内排序散列我有返回下列阵列的数据模型:红宝石具有麻烦阵列

[[54993, {:posted_at=>1363066554, :item_id=>55007,..}],..]

54993是POST_ID。我正在尝试使用这个数组并按posted_at排序。该数组通过posted_at正确排序。这里是我当前的代码:

post_ids = UserFeed.new(current_user.id).posts.collect{|x| x[0]} 
    posts = Post.where(:id => post_ids) 

这由post_id,不posted_at进行排序。我试图弄清楚如何按posted_at排序,并想知道为什么数组假设post_id

+0

是这个了activerecord ?无论如何,都要相应地标记它。如果是这样,我不明白“帖子”关联如何返回对。在AR中,当关联配置正确时,您可以编写'posts = UserFeed.new(current_user.id).posts.order(“posted_at ASC”)' – tokland 2013-03-12 21:56:56

回答

2

where(ids)没有设置顺序,它使用SQL IN (id1, id2, ...)。用ActiveRecord:

post_ids = UserFeed.new(current_user.id).posts.map(&:first) 
posts = Post.where(:id => post_ids).order("posted_at ASC") 

如果没有属性posts.posted_at,然后,溶液1:

posts = post_ids.map { |post_id| Post.find(post_id) } 

解决方案2:本执行单个查询,然后排序:

indexes = Hash[post_ids.map.with_index.to_a] 
posts = Post.where(:id => post_ids).sort_by { |p| indexes[p.id] } 
+0

BOOM!这个答案充满了胜利。你的第二个建议是正确的。我忘了在问题中提到'posted_at'不是帖子的保存属性。非常感谢! – jmohsenin 2013-03-12 23:30:01

0

那家真正改变的问题,问题的错字,使我想到,如果post_ids排序正确的第一件事就是:

posts = [] 

post_ids.each do |post_id| 
    posts << Post.find(post_id) 
end 
+0

对不起,错字,我的意思是'posted_at',而不是'created_at'。 – jmohsenin 2013-03-12 21:36:24

+0

好吧,这改变了一切.. – Zippie 2013-03-12 21:37:08

+0

此外,这是行不通的,因为它是一个数组中的散列。 – jmohsenin 2013-03-12 21:38:18

2

如果你真的需要在内存阵列而不是排序使用DB查询您的数据,试试这个:

method_that_returns_array.sort{ |a, b| a[1][:posted_at] <=> b[1][:posted_at]} 

但与查询排序的首选方式:

Post.order(:posted_at) 

希望它有帮助:)

+2

更短,更习惯,更快:'method_that_returns_array.sort_by {| x | x [1] [:posted_at]}' – tokland 2013-03-12 22:10:22

+0

感谢您的领导,每天我都会学到新的东西:) – sergelerator 2013-03-12 22:16:40

+0

不客气:-) http://en.wikipedia.org/wiki/Schwartzian_transform – tokland 2013-03-12 22:18:28