Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by either created_at or updated_at (whichever is more recent) Ruby on Rails

I am having what feels like a simple problem, except I can't seem to find the answer.

I have a group of records:

@mymonkeys = @user.monkeys.all

What I need are the 3 monkeys that have most recently been interacted with (either created or updated).

I can get the most recently created monkeys like this: @mymonkeys.sort_by(&:created_at).reverse!.take(3)

And the most recently updated monkeys like this: @mymonkeys.sort_by(&:updated_at).reverse!.take(3)

But is there a line of code that returns the monkeys that have most recently been either created or updated?

Thanks so much!



PS: I saw this question which mentioned the coalesce keyword but I wasn't able to determine whether or not that's what I'm looking for.

like image 532
PlacateTheCattin Avatar asked Oct 26 '25 15:10

PlacateTheCattin


1 Answers

&:created_at is syntax sugar for { |monkey| moneky.created_at }. Pass the block in which you do what you want.

@mymonkeys.sort_by { |m| [m.created_at, m.updated_at].max }.reverse!.take(3)
like image 186
falsetru Avatar answered Oct 29 '25 05:10

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!