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])
You can just do this instead:
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].
Using the hash at the end you could just pass this in as :time => Time.now and reuse :time in multiple places in your conditions hash. Neat.

Update: See ActiveRecord::Base on Noobkit for more info


Comments

  1. Zach Inglis Says:

    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.

  2. David Says:

    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.

  3. David Says:

    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

  4. Zach Inglis Says:

    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.

  5. Ivan Storck Says:

    I noticed I had to change the LIKE statement slightly to include the wildcard characters.

    :conditions => ["description LIKE :description", {:description => "%" + params[:description] + "%"}]
  6. David Says:

    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.

Sorry, comments are closed for this article.