1

I have a User model that has many Post.

I want to get, on a single query, a list of users IDs, ordered by name, and include the ID of their last post.

Is there a way to do this using the ActiveRecord API instead of a SQL query like the following?

SELECT users.id, 
    (SELECT id FROM posts 
     WHERE user_id = users.id 
     ORDER BY id DESC LIMIT 1) AS last_post_id
FROM users
ORDER BY id ASC;

1 Answer 1

2

You should be able to do this with the query generator:

User.joins(:posts).group('users.id').order('users.id').pluck(:id, 'MAX(posts.id)')

There's a lot of options on the relationship you can use to get data out of it. pluck is handy for getting values independent of models.

Update: To get models instead:

User.joins(:posts).group('users.id').order('users.id').select('users.*', 'MAX(posts.id) AS max_post_id')

That will create a field called max_post_id which works as any other attribute.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, works great! is there a way to return the users as ActiveRecord objects and still have access to the last post id? (even if I have to select all User columns)
Updated the answer with a way of getting models.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.