Hi, I’m Josh Symonds

I blog about Ruby on Rails, coding, and servers

Rails 3: Arel, Arel_Table, and Squeel

Reading time 1 minute

Rails 3 provides a lot of really neat functionality, and one of the pieces that looked coolest was Arel – ActiveRecord’s own relational algebra. Finally, we could get rid of SQL in queries and use a clear, syntactic DSL to manage our queries!

Well, in reality, that isn’t quite what happened. ActiveRecord’s Arel functionality does provide some neat criteria chaining methods, but unfortunately you either end of typing a lot of raw SQL:

1
2
Model.select("sum(model.column) as 'model_sum'").order("created_at
DESC").where("models.created_at > ?", DateTime.now - 1.day)

Or using unpleasant workarounds to address the underlying Arel for the model:

1
Model.where(Model.arel_table[:title].matches('%foo%'))

This is just kinda ugly. Happily, there’s a Gem that addresses this problem called squeel that makes Arel what, in my mind, it should be. It provides an elegant, simple syntax for creating and managing queries that is sensibly divorced both from the underlying Arel and raw SQL of the database:

1
Model.where{ {name == 'Josh' | created_at <= DateTime.now} }

Much easier to understand! The double-curly braces does kind of suck (this is because it’s a hash inside a proc) but it’s still a fair but more understandable than the default Arel stuff.

Josh Symonds performs devops and server wrangling on cloud-scale infrastructures, deploys amazing web applications with Ruby on Rails, and creates awesome iOS apps with Objective-C and RubyMotion. He is founder and CTO of Symonds & Son, a development shop focused on quality and excellence.

Josh Symonds