ActiveRecord and ARel: correlated subqueries?

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:[email protected]
http://www.schuerig.de/michael/