015 有趣的查询条件

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).
 
你可以传递复杂的查询条件。数组,区间和空值都可以作为查询条件。这节,你会看到利用这些东西作为查询条件的情况。
 
首先,来看看
#1
>>Task.count(:all, :conditions=>["complete=? and priority=? ", false, 3])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority=3)
=>2
#2
>>Task.count(:all, :conditions=>["complete=? and priority=? ", false, nil])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority=NULL)
=>0
 
在SQL中应该是IS NULL而不是=NULL
所以
>>Task.count(:all, :conditions=>["complete=? and priority IS ? ", false, nil])
 
在查询中也可以用到数组:
 
>>Task.count(:all, :conditions=>["complete=? and priority in ? ", false, [1,3]])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority IN (1,3))
=>3
 
也可以使用区间:
 
>>Task.count(:all, :conditions=>["complete=? and priority in ? ", false, 1...3])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority IN (0,1,2))
=>3
 
在rails1.2版本中,支持conditions适用hash:
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>1})
=>1
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>nil})
=>0
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>[1,3]})
=>3
 
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>1...3})
=>3
 




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/131625,如需转载请自行联系原作者
上一篇:并发编程(二):分析Boost对 互斥量和条件变量的封装及实现生产者消费者问题


下一篇:分层中的~条件过滤~每个层对于“条件过滤”的职责