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: