0

How can I group User by name and get only the most recent User for each name,

order(create_at: :desc)

I am already grouping my users by name but I can't get only the most recent for each name:

User.group(:id, :name).select(:id, :name, :created_at)

[EDIT 01]

Now I am tryint to get uniq users but also the most recent: Works!

User.order(upadted_at: :desc).uniq{ |u| u.name }
Lucas Andrade
  • 4,315
  • 5
  • 29
  • 50

2 Answers2

1

TRY This:

User.select([:id, :name]).order(created_at: :desc).group(:id, :name)

or

User.select([:id, :name]).order(:created_at).reverse_order.group(:id, :name)
rahul mishra
  • 1,390
  • 9
  • 16
0

You can check the active record documentation for more but you can do try this:

# This will give you the SELECT DISTINCT "users"."name" FROM "users" 
User.distinct.pluck(:name).take(2)

# You can also try this to order by created_at
User.select(:name).order(created_at: :desc)

# You can also take the one that appears first in the most recent 
User.select(:name).order(created_at: :desc).take(1)

You should also check this other answer

Hope this helps.

mayorsanmayor
  • 2,870
  • 4
  • 24
  • 44