Reputation: 35542
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.
Upvotes: 2
Views: 2575
Reputation: 8512
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 :).
Upvotes: 2