ActiveRecord[六]:find_by_sql()方法

上一篇 / 下一篇  2007-09-12 11:09:02 / 个人分类:rubyonrails学习笔记

1、接受完整的SQL select语句作为参数,并返回根据结果集创建的模型对象数组(可能为空),每个模型对象的属性会被设为对应记录的对应字段值
2、返回的结果对象只包含查询语句中指定的属性,可以用一些方法来查询模型对象拥有哪些属性,具体方法如下:
  attributes():返回对应于各个属性的名-值对
  attributes_names():返回属性名称组成的数组
  attributes_present?():返回true(如果该属性存在)false(如果模型对象没有该属性)
如:orders=Order.find_by_sql("select name,pay_type from orders")
   first=orders[0]
   p first.attributes
   p first.attributes_names
   p first.attributes_present?("address")
输出结果为:
   {"name"=>"Dave Thomas","pay_type"=>"check"}
   ["name","pay_type"]
   false
3、find_by_sql()可用于创建模型对象,并在其中放置派生字段的数据,如:
items=LineItem.find_by_sql("select *,                          "+
                           "quantity*unit_price as total_price,"+
                           "products.title as title            "+
                           "from line_items,products           "+
                           "where line_items.product_id=products.id")
li=items[0]
此时title和total_price都是li的属性
4、可以传入数组给find_by_sql()方法,如:
Order.find_by_sql(["select * from orders where amount > ?",params[:amount]])

TAG:

小飞猪之Ruby窝 引用 删除 drive2me   /   2007-09-15 15:59:56
好认真。
你的家真美!哈哈!
小飞猪之Ruby窝 引用 删除 drive2me   /   2007-09-15 15:59:50
5
 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2009-01-08  
    123
45678910
11121314151617
18192021222324
25262728293031

数据统计

  • 访问量: 461
  • 日志数: 19
  • 建立时间: 2007-08-30
  • 更新时间: 2007-11-27

RSS订阅

Open Toolbar