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


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| … }

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

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

articles = Article.with_latest_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 S.
mailto:[email protected]