Firstly, I've asked a similar question before[*]. I didn't get any answers back then, maybe now I have better luck
Let's say I have models like this
class Article < ActiveRecord::Base has_many :versions end
class Version < ActiveRecord::Base belongs_to :article default_scope order('updated_at') scope :published, where(:state => 'published') validates :state, :inclusion => { :in => ['draft', 'published'] } validates :title, :content, :presence => true end
It's easy to find the latest version for an article, just
article.versions.last
The same for published versions isn't much more complicated
articles.versions.published.last
Of course, I'm not only dealing with single articles
Article.all
Then, in a articles/_article.html.erb
<%= article.version.last.title %>
Oops! That triggers another database access for each article.
Now, I know how to deal with this in SQL, with either a correlated sub- select or an even more complicated left outer join. I've forced the first technique into ActiveRecord wrapping, which isn't fun. Far from being any help. ARec gets in the way. I've dabbled with ARel which was even worse, but may be due to my inexperience with it.
Currently, the nicest solution I can think of is to accept the SQL and go native: i.e., define a view in the database and a read-only model on top of it.
I appreciate any suggestions how to do this *elegantly* in ARec.
Michael
[*] 2010-06-20, ActiveRecord and ARel: correlated subqueries?