在新版本的Rails中,都推荐使用where而不是find方法进行条件查询了。
语法上和find条件查询差不多,应该说更简洁一点,比如我想找到position是2的对象。
1
2
3
4
|
irb(main): 090 : 0 >
Subject.where( "position=?" , "2" ).order( "name" ) =>
[ #<Subject
id: 4, created_at: "2012-10-20 15:14:07", updated_at: "2012-10-20 15:17:46", name: "Fourth Subject", posit ion:
"2" >,
#<Subject
id: 2, created_at: "2012-10-20 06:25:27", updated_at: "2012-10-20 15:10:36", name: "Second Subject" ,
position: "2" >] |
与find方法不同的是,where方法返回的结果不是数组而是ActiveRelation,这意味着我们可以基于当前的查询结果继续设置条件进行查询。
1
2
|
irb(main): 168 : 0 *
Subject.where( :position => "2" ). class =>
ActiveRecord::Relation |
并且,通过to_sql方法我们能看到Rails将我们的条件转换成的SQL语句以便于调试。
1
2
|
irb(main): 169 : 0 >
Subject.where( :position => "2" ).to_sql =>
"SELECT
`subjects`.* FROM `subjects` WHERE `subjects`.`position` = '2'" |
比如第一步先检索出position是2的所有对象,然后再根据name降序排列等等。
1
2
3
4
|
irb(main): 096 : 0 >
Subject.where( "position=?" , "2" ).order( "name
desc" ) =>
[ #<Subject
id: 2, created_at: "2012-10-20 06:25:27", updated_at: "2012-10-20 15:10:36", name: "Second Subject", posit ion:
"2" >,
#<Subject
id: 4, created_at: "2012-10-20 15:14:07", updated_at: "2012-10-20 15:17:46", name: "Fourth Subject" ,
position: "2" >] |
与find的另一点不同是,where是懒加载的。也就可以理解为通过where方法返回对象只是一个壳子,里面什么都没有,直到我们需要从这个对象中取得属性值这一刻才会真的查询数据库。如果想要关闭懒加载特性,在where调用之后增加.all即可。
下面说说where方法中的条件参数格式。
第一种是String,相当于直接传入SQL语句,为了防止SQL注入的风险,最好只用于硬编码或变量全部由我们自己控制的SQL语句,千万不要将用户输入的变量值直接放在语句里。
1
2
3
|
irb(main): 160 : 0 >
Subject.where( "position
= '2' AND name='Second Subject'" ) =>
[ #<Subject
id: 2, created_at: "2012-10-20 06:25:27", updated_at: "2012-10-20 15:10:36", name: "Second Subject", posit ion:
"2" >] |
第二种是Array,第一个参数和需要写的SQL语句格式完全一样,字段值的地方用?问号代替。后面的参数按照顺序提供条件值。
1
2
3
|
irb(main): 161 : 0 >
Subject.where( "position
= ? AND name=?" , "2" , "Second
Subject" ) =>
[ #<Subject
id: 2, created_at: "2012-10-20 06:25:27", updated_at: "2012-10-20 15:10:36", name: "Second Subject", posit ion:
"2" >] |
第三种是Hash,每个参数都是一套值对。这种方式非常简单直观,不过有点局限就是表现力有点差,只能表示AND,无法表示OR。
1
2
3
|
irb(main): 165 : 0 >
Subject.where( :position => "2" , :name => "Second
Subject" ) =>
[ #<Subject
id: 2, created_at: "2012-10-20 06:25:27", updated_at: "2012-10-20 15:10:36", name: "Second Subject", posit ion:
"2" >] |
所以选择用哪种条件表达式方式就得根据实际情况而定了,一般来说简单的查询使用Hash方式,当复杂性无法满足的时候使用Array型。至于String方式直接写SQL语句的最好还是别用了。
查询返回的结果可以当做一个Array使用,如果什么都没查到,返回的长度为0。
1
2
|
irb(main): 172 : 0 >
Subject.where( :position => "3" ) =>
[] |