这次我们来讨论一下关于find
方法查询条件的话题。以下是Rails Console输出的SQL查询语句。对应的动作是查找所有优先级为3的未完成任务。
>>Task.count(:all,:conditions=>["complete=? and priority=?,false,3]) =>2
对应的SQL查询是
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority=3);
查找所有优先级为3的未完成任务。
以上代码正常工作是没有问题的,可是如果想查找出所有优先级为nil
的任务呢?
Task.find(:all, :conditions > ["completed = ? AND priority = ?", false, nil])
难道要生成如下的SQL查询码?
SELECT * FROM "tasks" WHERE (completed = 'f' AND priority = NULL);
查询空值是生成了错误的SQL语句。
上面的查询不能工作,正确的写法应当是priority IS NULL
,priority = NULL
。同理,当查找多个优先级的条件时应当使用IN
而不是=
,并且得用小括号扩这备选值以便满足SQL语法
Task.find(:all, :conditions > ["completed = ? AND priority IN (?)", false, [1,3]])
我们期待的,正确语法的SQL语句是
SELECT * FROM "tasks" WHERE (completed = 'f' AND priority IN (1,3));
Task.find(:all, :conditions > { :completed > false, priority > [1,3] }
对应的SQL查询是
SELECT * FROM "tasks" WHERE (completed = 'f' AND priority IN (1,3)
使用hash作为查询条件及生成的SQL查询
Task.find(:all, :conditions > {:completed > false, priority > 2..4})
对应的SQL查询是
SELECT * FROM "tasks" WHERE ("tasks"."priority" BETWEEN 2 AND 4 AND "tasks"."completed" = 'f');
传入Range
会被转换为BETWEEN
字句。
在《RailsCasts中文版,#2 Dynamic find_by Methods 使用动态的find_by方法进行查找操作》 曾经介绍过find_by
方法。同样也支持hash和Range作为查询条件。
Task.find_by_priority(1..5)
对应的SQL查询是
SELECT * FROM "tasks" WHERE ("tasks"."priority" BETWEEN 1 AND 5) LIMIT 1;
作为结论,我们知道,为了保证生成正确格式的SQL查询语句,推荐使用hash格式的查询条件。
作者授权:Your welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.
原文链接:http://railscasts.com/episodes/15-fun-with-find-conditions