Its all about Ruby On Rails
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:
User.find(:all, :conditions=>{:first_name => ‘akhil’, :role => ‘admin’})
will generate SQL as “where `first_name` = ‘akhil’ and `role` = ‘admin’”
Also we can have range as condition
Example:
User.find(:all, :conditions => {:access_level => 3..5})
will generate SQL as “where `access_level` BETWEEN 3 AND 5″
This is really helpful modification in ActiveRecord
| Print article | This entry was posted by Akhil Bansal on February 22, 2007 at 12:56 am, and is filed under ROR, Rails, Rubyonrails, active_record. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 3 years ago
In what version of AR does this functionality appear?
about 3 years ago
Nice. How do you specify the OR condition?
about 3 years ago
Zerohalo,
Currently we have no way to specify ‘OR’
about 3 years ago
Hi zerohalo,
Try this for OR condition as:
:conditions=>["firstname =>:fname OR lastname => :lname", {:fname=> @fname, :lname => @lname}]
about 3 years ago
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?
about 3 years ago
I don’t have exact idea when it was introduced, but it was near rails 1.2.0