rails3高级查询

在modle中
查看文本 打印 ?
  1. class Student < ActiveRecord::Base  

  2.  attr_accessible :address, :age, :name, :sex

  3.  scope :address_is_beijing, where(:address => "beijing")  

  4. defself.younger_than(age)  

  5.    where("students.age < ?", age)  

  6. end

  7.  scope :myage, younger_than(21)  

  8. end

打开控制台,切换到工作目录后,执行rails c
查看文本 打印 ?
  1. scope :address_is_beijing, where(:address => "beijing")  

这句相当于给Student增加了类方法address_is_beijing, 执行Student.address_is_beijing, 查看输出结果
查看文本 打印 ?
  1. irb(main):001:0> Student.address_is_beijing  

  2.  [1m[36mStudent Load (0.0ms)[0m  [1mSELECT "students".* FROM "students" WHE  

  3. RE "students"."address" = 'beijing'[0m  

  4. => [#<Student id: 1, name: "zhangsan", age: 21, address: "beijing", sex: "man",

  5. created_at: "2012-09-02 04:44:43", updated_at: "2012-09-02 08:23:19">, #<Student

  6. id: 9, name: "zhaoliu", age: 24, address: "beijing", sex: "man", created_at: "2  

  7. 012-09-02 08:21:13", updated_at: "2012-09-02 08:21:13">]  

查看sql语句: Student.address_is_beijing.to_sql
查看文本 打印 ?
  1. irb(main):002:0> Student.address_is_beijing.to_sql  

  2. => "SELECT \"students\".* FROM \"students\"  WHERE \"students\".\"address\" = 'b  

  3. eijing'"  

同样,执行Student.myage 可以查询到年龄小于21的学生


你可能感兴趣的:(sql,Rails)