views:

31

answers:

1

Hi,

I want to perform an operation on a array returned from an ActiveRecord query. This is the functionality I would have done on the ActiveRecord directly.

Modification.find(:all, :group=>'ref_id,start_date', :order=>'updated_at desc')

The above is working fine as expected. But the problem is I cannot perform it directly for some reasons. But I have an array. I cannot use :group symbol on an array for the obvious reason that is not an ActiveRecord. But I would want the same functionality. Something like

modifications = Modification.all
modifications.find(:all, :group=>'ref_id,start_date').sort(:order=>&:updated_at)

The above one would not work for obvious reasons, but how to do a similar ActiveRecord implementation for the Array.

+1  A: 

If you want to sort before group:

modifications.group_by{|modification| "#{modification.ref_id}#{modification.start_date}"}.values.collect{|modification_array|
  modification_array.sort_by{|mod| mod.updated_at}.last
}

If you want to sort after:

modifications.group_by{|modification| "#{modification.ref_id}#{modification.start_date}"}.values.map(&:first).sort_by{|mod| mod.updated_at}.invert

Haven't tested :).

Vlad Zloteanu
Shadwell
You're right :) updated my answer
Vlad Zloteanu
Nice dude!!! Thank you very very very much..
Bragboy
You're welcome :)
Vlad Zloteanu