ActiveRecord::Relation (AKA ARel) is the desired result, it's all about lazy loading which enhances the ability seamlessly to do things like fragment caching, tagging an enumerable, such as .first, on to the end of an ARel result should then cause the actual query to be run.
The idea is that ruby is preparing the query to be run before it is actually needed. Using the ARel should then cause the SQL to be run.
wherever possible It is desirable to use ruby methods rather than direct SQL statements as Ruby has the arrogance (rightly so) to believe it will do a better job of :-
1) Optimising the query to be run as efficiently as possible.
2) Making sure that the SQL that is actually run is as close as possible to the correct syntax for the database used according the the adapter specified in the database.yml for the current environent (Development, Test, Production)
The idea is that this enables the developer to concentrate more on getting the desired results and less on worrying about the intended database that is going to be used.
It doesn't always work that way, but 99.9% of the time ruby is very very good at achieving both those objectives.
So given my solution that returns an ActiveRecord::Relation do you get the desired result when you tag on a .first? If not what is the error?
What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)