#15
Apr 06, 2007

Fun with Find Conditions

You can pass more than simple strings to find conditions. Arrays, ranges, and nil values can be passed as well. In this episode you will see the tricks involved with passing these odd objects to find conditions. (Update: audio fixed).
Download (17.5 MB, 4:31)
alternative download for iPod & Apple TV (8.2 MB, 4:31)
Task.find(:all, :conditions => ["complete=? and priority=?", false, 3])
Task.find(:all, :conditions => ["complete=? and priority IS ?", false, nil])
Task.find(:all, :conditions => ["complete=? and priority IN (?)", false, [1,3]])
Task.find(:all, :conditions => ["complete=? and priority IN (?)", false, 1..3])

Task.find(:all, :conditions => { :complete => false, :priority => 1 })
Task.find(:all, :conditions => { :complete => false, :priority => nil })
Task.find(:all, :conditions => { :complete => false, :priority => [1,3] })
Task.find(:all, :conditions => { :complete => false, :priority => 1..3 })

Task.find_all_by_priority(1..3)

10 comments

Sandro Jul 04, 2007 at 07:10

WOOW ! I've been looking for this for days !! Thanks a lot !


Bob Jul 19, 2007 at 12:05

Any idea how to specify exclusion criteria? For example, what is the syntax for excluding records with priority 1 & 3 using the hash for input.


Ryan Bates Jul 19, 2007 at 13:27

@Bob, I don't think that's possible. You'll have to use a string for the conditions.


Bob Jul 19, 2007 at 15:20

Thanks Ryan, that's what I thought, so I should specify "priority NOT IN (?)", in the string.


Mo Rashed Oct 27, 2007 at 08:19

Hi, how do you combine this with eagerLoading?

Task.find(:all, :include => projects, :conditions => ["tasks.complete=? and tasks.priority = ?", false, nil])

Does this work?

tHnx


kino May 23, 2008 at 01:55

I feel I have sufficiently shown this to be true.


Lucas Fais Jun 05, 2008 at 15:18

What the best way to do something like this:

Task.find(:all, :conditions => {:start.year => 2008})

without user database functions...

It's posssible?

Very good Rails screencasts!

Thank's


Prakash Jun 26, 2008 at 12:18

Thanks. This is what I was looking for!!


Daryl Jul 26, 2008 at 12:25

Is it just me or are neither of these videos working anymore? (404 not found)


Ryan Bates Jul 26, 2008 at 16:01

@Daryl, try it now, I forgot to fix the URL when changing the site.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(required)

subscribe:
sponsored by:
if you want to help:
required:
Get Quicktime Player