ActiveRecord finder: Now we can use hash as conditions


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:

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

Also we can have range as condition

Example:

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

This is really helpful modification in ActiveRecord :-)

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
Engine Yard: Best Hosting for rails applications
Delegation in rails

Reader Comments

In what version of AR does this functionality appear?

Nice. How do you specify the OR condition?

Zerohalo,
Currently we have no way to specify ‘OR’

Hi zerohalo,
Try this for OR condition as:

:conditions=>[”firstname =>:fname OR lastname => :lname”, {:fname=> @fname, :lname => @lname}]

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?

I don’t have exact idea when it was introduced, but it was near rails 1.2.0

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.