[英]Ruby having trouble sorting hash within array
我有一個返回以下數組的數據模型:
[[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
進行排序。
如果您確實需要內存中的數組而不是使用數據庫查詢對數據進行排序,請嘗試以下操作:
method_that_returns_array.sort{ |a, b| a[1][:posted_at] <=> b[1][:posted_at]}
但是使用查詢排序是首選方式:
Post.order(:posted_at)
希望能幫助到你 :)
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] }
問題中有一個錯誤確實改變了問題,所以我想到的第一件事是,如果post_ids正確排序,則:
posts = []
post_ids.each do |post_id|
posts << Post.find(post_id)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.