# Latest user post (many-to-many relation)

**URL:** <https://www.ruby-forum.com/t/latest-user-post-many-to-many-relation/187778>\
**Category:** Rails\
**Created:** [April 29, 2010, 5:14am UTC](https://www.ruby-forum.com/t/latest-user-post-many-to-many-relation/187778 "2010-04-29T05:14:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 29, 2010, 5:14am UTC](https://www.ruby-forum.com/t/latest-user-post-many-to-many-relation/187778/1 "2010-04-29T05:14:19Z")

</div>

Hello

I have a one-to-many relation between two tables, ‘users’ and ‘posts’,  
where User has\_many :posts and Post belongs\_to :user. I have a query  
which returns every user on the table, along with the content of their  
latest post, if any, as follows:

```
@users = User.find_by_sql <<-EOQ
  SELECT
    u.name, p1.content
  FROM
    users u
  LEFT JOIN posts p1 ON (u.id = p1.user_id)
  LEFT OUTER JOIN posts p2 ON
    (u.id = p2.user_id AND
     (p1.created_at < p2.created_at OR
      p1.created_at = p2.created_at AND p1.id < p2.id))
  WHERE p2.id IS NULL
EOQ

```

Is there a way to make this more idiomatic by using Active Record’s  
query interface? I’m using Rails 3.

Thanks,  
Andre
