ORMQL (Object Relational Mapping Query Language) is a very simple query language to retrieve ActiveRecord objects from a database. It consists in the standard SQL where the FORM part is eliminated and column names are substituted by ActiveRecord attributes names, including nested associations. It is not necessary to learn any new language because ORMQL is a simple substitution of relevant parts in the query string and the result is sent to database as normal query.
ORMQL Rails plugin adds two methods to ActiveRecord::Base class, find_by_ormql and count_by_ormql
The advantage of using find_by_ormql over normal finder find is that the eager loading is unlimited and automatic.
Having these models:
class Author < ActiveRecord::Base
belongs_to :country
has_many :articles
has_many :comments
end
class Country < ActiveRecord::Base
has_many :authors
end
class Article < ActiveRecord::Base
belongs_to :author, :class_name => 'User'
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :article
belongs_to :author, :class_name => 'User'
end
Now I can make this query:
for user in User.find_by_ormql('SELECT nick, country.name, articles.comments.title WHERE surname=? ORDER BY country.name', 'Llorach')
puts "#{user.nick} is from #{user.country.name} and has written by example the comment #{article.comment.title}"
end
The latest version of ORMQL Rails plugin can be found at http://rubyforge.org/projects/ormql/
See also Plugins