Reputation: 2121
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
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)
Upvotes: 1