Ruby on Rails: Quick tip for Find :conditions
11 January 2008 I stumbled across a sneaky tip for conditions when using find. When you might normally be doing this:
1 2 |
Account.find(:all, :conditions => ['name LIKE ? AND updated_at < ?', "aname", 3.days.ago]) |
1 2 |
Account.find(:all, :conditions => ['name LIKE :name AND updated_at < :date', {:name => "aname", :date => 3.days.ago}]) |
This isn't the best example of using this symbol placeholder method, but imagine using it in a situation where you're repeating the same search param a few times. I know I've had a few times that my conditions has been something like
1 2 |
['created_at > ? AND updated_at < ? AND invoiced_at > ?'], Time.now, Time.now, Time.now]. |
Update: See ActiveRecord::Base on Noobkit for more info
Comments
Sorry, comments are closed for this article.

Feed me


January 28, 2008 at 08:01 AM
Maybe I am misunderstanding but don’t you mean: Account.find(:all, :conditions => { :name => “aname”, :date => 3.days.ago }) ?
Your docs a bit old? :D
When I first started all those years ago I hated using the text method, the latter hash matching is much prettier and feels generally more Ruby and takes away the hacky ORM feel.
January 28, 2008 at 08:07 AM
Yeah, obviously that’s one route you can take.
But when you’re using IN or LIKE or want to use the SQL % wildcard in your queries then the way you suggest doesn’t cut it.
I think the way you’re describing is great, but the other method is still very valid and oft used.
January 28, 2008 at 08:47 AM
Interestingly, I just had a look at the Rails docs and it looks like they mention the symbol placeholder method there (I hadn’t seen it before, but it does seem to exist in the 1.2 docs).
On the hash method – the docs say “The hash form works much like the array form, except only equality and range is possible.”
I agree with you, it is a nicer and more readable way to do queries – I just find myself doing it less frequently than the array method.
See ActiveRecord::Base
January 28, 2008 at 11:01 PM
Totally.
Until they take it away from a hash and build some sort of psuedo method (god forbid) where other operators are allowed, then array is the best chance. I prefer a one-text liner but of course as we know, not so safe.
February 21, 2008 at 08:36 AM
I noticed I had to change the LIKE statement slightly to include the wildcard characters.
:conditions => ["description LIKE :description", {:description => "%" + params[:description] + "%"}]March 07, 2008 at 01:49 PM
I’d personally favour doing that like this to cut down on space…
{:description => "%#{params[:description]}%"}But of course you are right to suggest that, sorry I missed it the first time around.