Sort an Array of ActiveRecords objects by created_at

Hi,
I have an array of activerecords objects. I’d like to sort it by
created_at column (they all have one).
Do you see a smart way to do it ??

Thanks,

Mike

what’s wrong with:

@my_model = Model.find(:all, :order => “created_at ASC”))

My array is composed by different activerecord objects:

my_model1 = Model.find(:all)

my_model2 = Model.find(:all)

@my_models = my_model1 + mymodel2

and now i’d like to sort @my_models by “created_at”

On Fri, Oct 24, 2008 at 10:59 AM, Bensoussan M.
[email protected]wrote:

My array is composed by different activerecord objects:

my_model1 = Model.find(:all)

my_model2 = Model.find(:all)

@my_models = my_model1 + mymodel2

and now i’d like to sort @my_models by “created_at”

@my_models = @my_models.sort_by { |m| m.created_at }

Note that Enumerable#sort_by returns a new array.

Regards,
Craig

Even simpler:

my_model1 = Model.find(:all)
my_model2 = Model.find(:all)

@my_models = (my_model1 + mymodel2).sort_by( &:created_at )

On Fri, Oct 24, 2008 at 12:12 PM, Bensoussan M. [email protected]
wrote:

Yes that’s it ! !

Thank you,
Mike.


Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)
João Pessoa, PB, +55 83 8867-7208

Yes that’s it ! !

Thank you,
Mike.

On Oct 24, 5:10 pm, “Craig D.” [email protected]

Thanks Maurício,

On Oct 24, 5:15 pm, “Maurício Linhares” [email protected]
wrote:

Even simpler:

my_model1 = Model.find(:all)
my_model2 = Model.find(:all)

@my_models = (my_model1 + mymodel2).sort_by( &:created_at )

What the ‘&’ do precisely ?

Hi Michael,

The &:created_at is just a shorthand for &Proc.new { |i| i.created_at }

On Fri, Oct 24, 2008 at 12:18 PM, Bensoussan M. [email protected]
wrote:

@my_models = (my_model1 + mymodel2).sort_by( &:created_at )


Maurício Linhareshttp://alinhavado.wordpress.com/(pt-br) |http://blog.codevader.com/(en)
João Pessoa, PB, +55 83 8867-7208


Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)
João Pessoa, PB, +55 83 8867-7208

excellent ! Thanks for the tip.

Mike

On Oct 24, 5:31 pm, “Maurício Linhares” [email protected]

On Oct 24, 4:31 pm, “Maurício Linhares” [email protected]
wrote:

Hi Michael,

The &:created_at is just a shorthand for &Proc.new { |i| i.created_at }

Although it should be noted that this (also known as Symbol#to_proc)
is a lot slower than just writing the equivalent block (but not in
ruby 1.9 or if my memory is correct, 1.8.7)

Fred

excellent ! Thanks for the tip.

Mike

On Oct 24, 5:31 pm, “Maurício Linhares” [email protected]