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"

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

Note that Enumerable#sort_by returns a new array.

Regards,
Craig

Yes that's it ! !

Thank you,
Mike.

Even simpler:

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

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

Thanks Maurício,

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 }

excellent ! Thanks for the tip.

Mike

excellent ! Thanks for the tip.

Mike

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