Topic: Sorting ActiveRecord results out of the database

Hello,
I need to sort the results coming out from the database based on an array...
Let me explain better smile

I have something like this:
@results = Ad.select("ads.*, ... ") ...

That returns me an array of Ad objects
Then I have an array of ad.id in a given order: my_preferred_order = [123, 543, 78, 22, ...]

I need to get @results sorted with Ads in the array order...
How can I do that?

Thank you all.

Last edited by nimbuz77 (2012-12-14 04:19:29)

Re: Sorting ActiveRecord results out of the database

Just use standard Array methods 'map' and 'sort':

@results = Ad.all.map{ |ad| ad.id}.sort

Re: Sorting ActiveRecord results out of the database

Javix wrote:

Just use standard Array methods 'map' and 'sort':

@results = Ad.all.map{ |ad| ad.id}.sort

I don't think you get my question.
I need to have the ads in the order specified in the second array...

Re: Sorting ActiveRecord results out of the database

my_preferred_order = [123, 543, 78, 22, ...]
ads = []

my_preferred_order.each do |ad|
   ads << Ad.find(ad.to_i)
end


puts ads.inspect

Re: Sorting ActiveRecord results out of the database

What about to create a new ActiveRecord::Relation object?
Because of further methods I need to have an ActiveRecord::Relation object instead of an array

Thanks for your help