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.
&: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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With