Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Clever Find Conditions in Rails without SQL

By Peter Cooper / June 8, 2006

Ryan Daigle reports that the latest 'edge Rails' has a cool new feature that lets you specify find conditions more logically. For example:

Post.find(:first, :conditions => ['status = ? and active = ?', 1, 1])

.. becomes:

Post.find(:first, :conditions => { :status => 1, :active => 1 })

I've accidentally tried to use this style before, and am glad it's now an approved part of Rails. If you're running edge Rails, you should have access to it as soon as you update, otherwise wait for Rails 1.2 :)

If this tickles your fancy, you might also want to check out ez_where by Ezra Zygmuntowicz that lets you do insanely cool stuff like:

articles = Article.ez_find(:all, :include => :author) do |article, author|
  article.title =~ "%Foo Title%"
  author.any do
    name == 'Ezra'
    name == 'Fab'

Yes, abstraction rules.


  1. Michael Gorsuch says:

    This RULES. Now (if I'm thinking about this correctly), I can pass a simple hash that I build from parameters of a form.

    For example, a search form. I no longer have to think out all of the cases of what combinations of form fields a user may or may not populate. I can simply take what he or she does, transform that into a hash, and pass it.


  2. Mr eel says:

    Well, if you wanted to something like that, you still need to be aware of users putting SQL statements into an input.

    I wonder if conditions passed in via a hash are getting sanitised? If they are, it removes the danger from doing what you suggest.

Other Posts to Enjoy

Twitter Mentions