0

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.

Chris Travers
  • 25,424
  • 6
  • 65
  • 182
sonnyhe2002
  • 2,091
  • 3
  • 19
  • 31
  • see here: http://stackoverflow.com/questions/4255286/rails-3-group-field-sorted-by-created-at-desc – tommyd456 Nov 11 '13 at 19:31
  • Ok, I dont need to use group, but i just want some query that returns the attempt if it is the lastest attempt for that student. For a set of attempts – sonnyhe2002 Nov 11 '13 at 19:35
  • Maybe something like: `Attempt.where(:user_id => user_id).order("created_at DESC").first` – tommyd456 Nov 11 '13 at 19:41
  • not tested this though so give it a try - I'm sure someone else will pitch in if I'm wrong – tommyd456 Nov 11 '13 at 19:42
  • I dont think you are interpreting the question correctly. I want an activerecord array of attempts as the result where each attempt must have a unique user and that attempt is the last attempt for that user. – sonnyhe2002 Nov 11 '13 at 22:30
  • ahhh did you get your answer 6 years later? – Benjamints Sep 16 '19 at 15:36

1 Answers1

1

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

Community
  • 1
  • 1
Le Droid
  • 4,534
  • 3
  • 37
  • 32