ActiveRecord finder: Now we can use hash as conditions

Published on Author Akhil Bansal6 Comments

Earlier conditions can either be specified as a string or array now in edge rails we can specify hash also. So if we specify conditions as hash then it will generate conditions based on equality with SQL AND.

Example:

[source:ruby]User.find(:all, :conditions=>{:first_name => ‘akhil’, :role => ‘admin’}) [/source]

will generate SQL as “where `first_name` = ‘akhil’ and `role` = ‘admin'”

Also we can have range as condition

Example:

[source:ruby]User.find(:all, :conditions => {:access_level => 3..5})[/source]

will generate SQL as “where `access_level` BETWEEN 3 AND 5”

This is really helpful modification in ActiveRecord :-)

6 Responses to ActiveRecord finder: Now we can use hash as conditions

  1. This is great. I’ve long thought the current way was cumbersome and not keeping with The Rails Way.

    I mean, nearly everything else is Model.method(:param => :value) except find().

    When I say not keeping with The Rails Way, I mean that it’s putting the user right into the muck. You don’t write SQL anywhere else in the app (excluding find_by_sql()), so how can we expect a user to know how to properly format a WHERE clause?

    Again, great news. In which version of Rails will this appear?

Leave a Reply

Your email address will not be published. Required fields are marked *