ruby where用法

用法1

Subject.where("position=?","2").order("name")  

用法2  

与find方法不同的是,where方法返回的结果不是数组而是ActiveRelation,这意味着我们可以基于当前的查询结果继续设置条件进行查询。

Subject.where(:position =>"2").class  
=> ActiveRecord::Relation 

用法3

通过to_sql方法我们能看到Rails将我们的条件转换成的SQL语句以便于调试

Subject.where(:position =>"2").to_sql  
=> "SELECT `subjects`.* FROM `subjects`  WHERE `subjects`.`position` = '2'"  

用法4

比如第一步先检索出position是2的所有对象,然后再根据name降序排列等等

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">]  

 

posted @ 2017-11-03 11:08  lmg6406  阅读(1034)  评论(0编辑  收藏  举报