Reputation: 2337
Easy one i think/hope... I have a query that returns a list of 20 unique foreign keys:
@results = Report.select("distinct user_id").where("datetime_utc >= ? AND datetime_utc <= ?",@utc_time_slot , @utc_time_slot_end).order("score DESC, quality DESC").limit(20)
this returns an array (ActiveRecord::Relation class):
[#<Report user_id: 803>, #<Report user_id: 809>, #<Report user_id: 806>, #<Report user_id: 801>, #<Report user_id: 830>, #<Report user_id: 860>, #<Report user_id: 858>, #<Report user_id: 856>, #<Report user_id: 854>, #<Report user_id: 852>, #<Report user_id: 851>, #<Report user_id: 850>, #<Report user_id: 849>, #<Report user_id: 846>, #<Report user_id: 859>, #<Report user_id: 866>, #<Report user_id: 2022>, #<Report user_id: 863>, #<Report user_id: 862>, #<Report user_id: 838>]
What do i need to do with this @results array to extract the collection of users form the users table that the user_id list refers to (in the same order)?
Thanks!
Upvotes: 0
Views: 1655
Reputation: 2142
You have two options for preserving order. First - eager load users in original query. In this case
users = @results.map(&:user)
Second - reorder on ruby side
idx = User.find(@results.map(&:user_id)).index_by(&:id)
users = @result.map{|r| idx[r.use_id]}
Upvotes: 1
Reputation: 474
Hej, First of all you need to prepare the array of user_ids. it should look like this [209, 902, ..., 890] (you can use map or collect method to do that) then just build sql query like that:
User.where(:id=>user_ids)
where the user_ids is prepared array
Upvotes: 0