I have a user model and a map model. The user has many cards, so the card has an attribute user_id.
I want to get the newest single Card for each user. I was able to do this:
Card.all.order(:user_id, :created_at)
This gives me half way, and I could, of course, iterate over these lines and grab the first one for each user. But it smells really bad to me, since I do a lot with arrays in Ruby.
I can also do this:
Card.select('user_id, max(created_at)').group('user_id')
# => gives me user_id and created_at
... but I only return user_ids and created_at timestamps. I cannot select any other columns (including the identifier), so what I get is useless. I also don't understand why PG won't let me select more columns than above without putting them in group_by or aggregate function.
I would rather find a way to get what I want using only ActiveRecord. I also want to write this query in raw SQL, but if I cannot do it with AR. BTW, I am using DB Postgres, which limits some of my options.
Thanks guys.
gregb source
share