# ActiveRecord and ARel: correlated subqueries?

**URL:** <https://www.ruby-forum.com/t/activerecord-and-arel-correlated-subqueries/190462>\
**Category:** Rails\
**Created:** [June 20, 2010, 11:51pm UTC](https://www.ruby-forum.com/t/activerecord-and-arel-correlated-subqueries/190462 "2010-06-20T23:51:58Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![wickie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/ba9def/32.png) [@wickie](https://www.ruby-forum.com/u/wickie)\
**Post date:** [June 20, 2010, 11:51pm UTC](https://www.ruby-forum.com/t/activerecord-and-arel-correlated-subqueries/190462/1 "2010-06-20T23:51:58Z")

</div>

I’m trying to figure out how to use ActiveRecord in conjunction with  
ARel. In particular, I’d like to replace my residual literal SQL with  
ARel, if only I could see how.

Let’s take Article with multiple Versions as an example. With ARel  
alone, I can find articles with their latest versions like this

articles = Article.arel\_table  
versions = Article.arel\_table

articles.join(versions).on(articles[:id].eq(versions[:article\_id])).  
where(versions[:revision].eq(  
versions.project(versions[:revision].maximum).  
where(versions[:article\_id].eq(articles[:id]))))

That doesn’t help me much in the context of ActiveRecord. There, I’d  
like to define things like this

class Article \< ActiveRecord::Base  
has\_many :versions  
has\_one :version  
scope :with\_latest\_version, …  
scope :with\_nth\_version, lambda { |n| … }  
end

class Version \< ActiveRecord::Base  
scope :latest, …  
end

In Rails 2.3.8, I have defined all this with the judicious help of some  
SQL. In Rails 3 I’d like to use ARel.

If you’re wondering what the point of Article#version is: it points to a  
version that is determined by the query used to retrieve the object. So  
for

articles = Article.with\_latest\_version

article[i].version

is intended to be the latest version. Works nicely in 2.3.8, but in  
3.beta4 it breaks down somewhere when ARel somewhere deep down doesn’t  
remember anymore that there is a :version association.

Michael

–  
Michael S.  
[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
[http://www.schuerig.de/michael/](http://www.schuerig.de/michael/)
