Q:

How to write this MySQL query using ActiveRecord

I'm working with a Rails 5 project and have a SQL query that looks like the following:
SELECT foo1.*  
 FROM foos foo1 
 WHERE foo1.created_at = 
   ( SELECT MIN(foo2.created_at) FROM foos foo2 WHERE foo2.user_id = foo1.user_id );

The model here is named Foo and the underlying table is named foos.  I want to write a method that'll basically give me one record per user_id with the earliest created_at timestamp which the SQL query above will solve.  I just want to write it using ActiveRecord. 

A:

The initial query you have doesn't necessarily give you one record per user_id. 
Here's an example:
# created_at1 < created_at2
foo1 = Foo.create!(user_id: 1, created_at: created_at1)
foo2 = Foo.create!(user_id: 1, created_at: created_at2)
foo3 = Foo.create!(user_id: 2, created_at: created_at2)

Your query will select the minimum created_at for each user_id, so it will get created_at1 from foo1 and created_at2 from foo3.  But since foo2 and foo3 share the same created_at, all three records will be returned. 
A better way to select the records would be (For Postgres):
Foo.select('DISTINCT ON ("user_id") *').order(:user_id, created_at: :asc)

