Sort an Array of ActiveRecords objects by created_at


#1

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


#2

what’s wrong with:

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


#3

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”


#4

On Fri, Oct 24, 2008 at 10:59 AM, Bensoussan M.
removed_email_address@domain.invalidwrote:

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


#5

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. removed_email_address@domain.invalid
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


#6

Yes that’s it ! !

Thank you,
Mike.

On Oct 24, 5:10 pm, “Craig D.” removed_email_address@domain.invalid


#7

Thanks Maurício,

On Oct 24, 5:15 pm, “Maurício Linhares” removed_email_address@domain.invalid
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 ?


#8

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. removed_email_address@domain.invalid
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


#9

excellent ! Thanks for the tip.

Mike

On Oct 24, 5:31 pm, “Maurício Linhares” removed_email_address@domain.invalid


#10

On Oct 24, 4:31 pm, “Maurício Linhares” removed_email_address@domain.invalid
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


#11

excellent ! Thanks for the tip.

Mike

On Oct 24, 5:31 pm, “Maurício Linhares” removed_email_address@domain.invalid