ruby condition

class.new 新建
class.find 查询
class.destroy 删除

变量查询
a="hahaha"
Product.find(:all,:conditions=>["title like ?","%#{a}%"])
Product.find(:all,:conditions=>["title like :title",:title=>"%#{a}%"])
Product.find(:all,:conditions=>["title like :title and price>:price",:title=>"%#{a}%",:prcie=>3])
相当
SELECT * FROM "products" WHERE (title like '%a%' and price>3)

字符串查询
Product.find(:all,:conditions=>{:title=>"a"})
相当
SELECT * FROM "products" WHERE ("products"."title" = 'a')

多条件查询合并
>> cs = [{:title=>"a",:price=>(1..20),:description=>"hhhhh"}, "title like '%b%'"]
=> [{:price=>1..20, :title=>"a", :description=>"hhhhh"}, "title like '%b%'"]
>> Product.all :conditions=> Product.merge_conditions(*cs)
相当
SELECT * FROM "products" WHERE (("products"."title" = 'a' AND "products"."price" BETWEEN 1 AND 20 AND "products"."description" = 'hhhhh') AND (title like '%b%'))

把条件设置数组
>> conditions = [] #定义一个数组
=> []
>> conditions << ["title like ?", 'a'] #把一个条件加到数组
=> [["title like ?", "a"]]
>> conditions << ["title like ?", 'a'] if params[:title].present? #加一个判断 非空时加入到数组

include附加查询(减少N+1次查询)
LineItem.all :conditions => "products.title => 'a'", :include => :product

jions附加查询
LineItem.all :conditions => "products.title like '%a%'", :joins => :product
想当
SELECT "line_items".* FROM "line_items" INNER JOIN "products" ON "products".id = "line_items".product_id WHERE (products.title like '%a%')

select查询
Product.find(:all,:select=>"title,price")
相当
SELECT title,price FROM "products"

readonly只读查询
>> p=Product.first
=> #.....
>> p=Product.first(:readonly=>true)
=> #....
>> p.title="xxxxxxxxx"
=> "xxxxxxxxx"
>> p.save #抛出异常

from 指定表名
group 指定分组
limit 指定条数
offset 指定起始数
find_by_sql 直接执行sql语句

获取字段统计信息
Product.average(:price)
Product.maximum(:price)
Product.minimum(:price)
Product.sum(:price)
Product.count()

动态查询
Product.find_by_title_and_price("测试",78.9) #只查第一条first 结果:title和price
Product.find_all_by_title_and_price("测试",78.9) #返回数组 结果:title和price
Product.find_or_create_by_title("hahahaha") #查询并保存
Product.find_or_initialize_by_title("aoiokkok") #查询,如果没有初始化


查看日志
tail -f log/development.log

原文地址:https://www.cnblogs.com/liugang/p/3209498.html