toamitkumar's Code Blog

Ruby, Rails, RubyMotion, Chef, Puppet, Play and others. Opinions expressed here are my own and do not reflect those of my employer.

Binding Variables in ARel

| Comments

Just wanted to quickly share the awesome new ActiveRecord Relational Algebra. I am sure there are many others but this one is a gem.

For long conditions like these:

Post.where(“(body like ? OR subject like ?) AND comment_count > ? AND created_at > ?”, criteria, criteria, 5, 3.days.ago)

It becomes really difficult to match the order of parameters.
Welcome to ARel, the same query can be written as:

Post.where(“(body like :criteria OR subject like :criteria) AND comment_count > :count AND created_at > created_date”, :criteria => criteria, :count => 5, :created_date => 3.days.ago)

See the binding variables in place of hard to remember question marks. It is important to note, in case the same variable is repeated multiple times, passing the variable once is sufficient.

More goodies to come !!

Comments