sonnyhe2002
sonnyhe2002

Reputation: 2121

How do I get the latest records depending on the foreign key

I am using rails with postgres. I have a table called 'attempts' which belongs to a 'users' table. I want to retrieve all attempts but only show the latest attempt for each user.

So I want code something like this:

Attempt.group(:user_id).having('latest(created_at)')

The above code does not work.

Upvotes: 0

Views: 288

Answers (1)

Le Droid
Le Droid

Reputation: 4774

I don't know Rails but it could be that "latest" doesn't exists in Postgresql. Could try with ...having('max(created_at)')

Otherwise this should do the job:

sql = "Select user_id, max(created_at) from attempt group by user_id"
records_array = ActiveRecord::Base.connection.execute(sql)

Inspiration source

Upvotes: 1

Related Questions