1、獲取數(shù)據(jù)
獲取第一條、最后一條記錄
復(fù)制代碼 代碼如下:
Model.first
Model.first(options)
Model.find(:first, options)
Model.last
Model.last(options)
Model.find(:last, options)
通過(guò)id獲取記錄
復(fù)制代碼 代碼如下:
Model.find(1, 10, options)
Model.find([1, 10], options)
.find all
復(fù)制代碼 代碼如下:
Model.all(options)
對(duì)一組數(shù)據(jù)進(jìn)行相同操作
復(fù)制代碼 代碼如下:
User.all.each do |user|
NewsLetter.weekly_deliver(user)
end
如果表記錄數(shù)比較大,這種方式比較耗資源,因?yàn)樗鼤?huì)一次載入整個(gè)表的數(shù)據(jù)。改用以下這種方式,它每次只載入1000行,然后逐步y(tǒng)ield完整個(gè)表
復(fù)制代碼 代碼如下:
User.find_each do |user|
NewsLetter.weekly_deliver(user)
end
自定義方式,find_each接受和find同樣的options
復(fù)制代碼 代碼如下:
User.find_each(:batch_size => 5000, :start => 2000) do |user|
NewsLetter.weekly_deliver(user)
end
find_in_batches,和find_each相似,但它yield時(shí)傳遞的是model對(duì)象數(shù)組,而不是單個(gè)model對(duì)象
復(fù)制代碼 代碼如下:
Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
export.add_invoices(invoices)
end
2、查詢條件
通過(guò)替換?來(lái)傳遞條件值,可避免SQL注入
復(fù)制代碼 代碼如下:
Client.first(:conditions => ["orders_count = ?", params[:orders])
symbol占位條件
復(fù)制代碼 代碼如下:
Client.all(:conditions => ["created_at >= :start_date AND created_at = :end_date", {:start_date => params[:start_date], :end_date => params[:end_date] }])
范圍條件 in(集合)
復(fù)制代碼 代碼如下:
Client.all(:conditions => ["created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date])
生成sql
復(fù)制代碼 代碼如下:
SELECT * FROM users WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05', '2008-01-06','2008-01-07','2008-01-08'))
如果要生成日期時(shí)間,再加上.to_time
復(fù)制代碼 代碼如下:
params[:start_date].to_date.to_time,生成2007-12-01 00:00:00格式
有上數(shù)據(jù)庫(kù)會(huì)在以上條件中報(bào)錯(cuò),如Mysql會(huì)報(bào)查詢語(yǔ)句過(guò)長(zhǎng)的錯(cuò)誤,此時(shí)可以改成created_at > ? AND created_at ?的形式
Hash條件
復(fù)制代碼 代碼如下:
Client.all(:conditions => {:locked => true })
帶范圍條件
復(fù)制代碼 代碼如下:
Client.all(:conditons => {:created => (Time.now.midnight - 1.day)..Time.now.midnight})
生成sql
復(fù)制代碼 代碼如下:
SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
集合條件
復(fù)制代碼 代碼如下:
Client.all(:conditons => {:orders_count => [1,3,5])
生成sql
復(fù)制代碼 代碼如下:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
3、查詢選項(xiàng)
排序
復(fù)制代碼 代碼如下:
#單個(gè)排序
Client.all(:order => "created_at ASC")
#多個(gè)排序
Client.all(:order => "orders_count ASC, created_at DESC")
返回指定字段
復(fù)制代碼 代碼如下:
Client.all(:select => "viewable_by, locked")
#使用函數(shù)
Client.all(:select => "DISTINCT(name)")
限定和偏移Limit and Offset
復(fù)制代碼 代碼如下:
Client.all(:limit => 5)
#生成
SELECT * FROM clients LIMIT 5
Client.all(:limit => 5, :offset => 5)
#生成
SELECT * FROM clients LIMIT 5, 5
Group分組
復(fù)制代碼 代碼如下:
Order.all(:group => "date(created_at)", :order => "created_at")
生成sql
復(fù)制代碼 代碼如下:
SELECT * FROM orders GROUP BY date(created_at)
Having
復(fù)制代碼 代碼如下:
Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago)
生成sql
復(fù)制代碼 代碼如下:
SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
只讀
復(fù)制代碼 代碼如下:
client = Client.first(:readonly => true)
client.locked = false
client.save
#對(duì)只讀對(duì)象進(jìn)行保存將會(huì)觸發(fā)ActiveRecord::ReadOnlyRecord異常
更新時(shí)鎖定記錄
樂(lè)觀鎖Optimistic Locking
為使用樂(lè)觀鎖,須在表里建一個(gè)lock_version的字段,每次更新記錄時(shí),ActiveRecord自動(dòng)遞增lock_version的值,
復(fù)制代碼 代碼如下:
c1 = Client.find(1) c2 = Client.find(1) c1.name = "Michael" c1.save c2.name = "should fail" c2.save # Raises a ActiveRecord::StaleObjectError
備注:You must ensure that your database schema defaults the lock_version column to 0.
This behavior can be turned off by setting ActiveRecord::Base.lock_optimistically = false.
指定樂(lè)觀鎖字段名
復(fù)制代碼 代碼如下:
class Client ActiveRecord::Base set_locking_column :lock_client_column end
悲觀鎖Pessimistic Locking
悲觀鎖定由數(shù)據(jù)庫(kù)直接提供
復(fù)制代碼 代碼如下:
Item.transaction do
i = Item.first(:lock => true)
i.name = 'Jones'
i.save
end
Mysql執(zhí)行返回
復(fù)制代碼 代碼如下:
SQL (0.2ms) BEGIN Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1 SQL (0.8ms) COMMIT
為特定數(shù)據(jù)庫(kù)加入原始的lock聲明
為Mysql的鎖定聲明為共享模式,即鎖定時(shí)仍然可讀
復(fù)制代碼 代碼如下:
Item.transaction do i = Item.find(1, :lock => "LOCK IN SHARE MODE") i.increment!(:views) end
4、關(guān)聯(lián)表
復(fù)制代碼 代碼如下:
Client.all(:joins => "LEFT OUTER JOIN address ON addresses.client_id = clients.id')
生成sql
復(fù)制代碼 代碼如下:
SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
使用Array、Hash、Named Associations關(guān)聯(lián)表
有如下model
復(fù)制代碼 代碼如下:
class Category ActiveRecord::Base
has_many :posts
end
class Post ActiveRecord::Base
belongs_to :category
has_many :comments
has_many :tags
end
class Comments ActiveRecord::Base
belongs_to :post
has_one :guest
end
class Guest ActiveRecord::Base
belongs_to :comment
end
復(fù)制代碼 代碼如下:
#關(guān)聯(lián)一個(gè)關(guān)系
Category.all :joins => :posts
#關(guān)聯(lián)多個(gè)關(guān)系
Post.all :joins => [:category, :comments]
#嵌套關(guān)聯(lián)
Category.all :joins => {:posts => [{:comments => :guest}, :tags]}
為關(guān)聯(lián)查詢結(jié)果設(shè)定條件
復(fù)制代碼 代碼如下:
time_range = (Time.now.midnight - 1.day)..Time.now.midnight Client.all :joins => :orders, :conditions => {'orders.created_at' => time_ran
#或者
time_range = (Time.now.midnight - 1.day)..Time.now.midnight Client.all :joins => :orders, :conditions => {:orders => {:created_at => time_range}}
5、優(yōu)化載入
以下代碼,需要執(zhí)行1 + 10次sql
復(fù)制代碼 代碼如下:
clients = Client.all(:limit => 10) clients.each do |client|
puts client.address.postcode
end
優(yōu)化:
復(fù)制代碼 代碼如下:
clients = Client.all(:include => :address, :limit => 10)
clients.each do |client|
puts client.address.postcode
end
一次性載入post的所有分類和評(píng)論
復(fù)制代碼 代碼如下:
Post.all :include => [:category, :comments]
載入category為1的所有post和cooment及tag
復(fù)制代碼 代碼如下:
Category.find 1, :include => {:posts => [{:comments => :guest}, :tags]}
6、動(dòng)態(tài)查詢
復(fù)制代碼 代碼如下:
Client.find_by_name("Ryan")
Client.find_all_by_name("Ryan")
#!方法,沒(méi)有記錄時(shí)拋出ActiveRecord::RecordNotFound異常
Client.find_by_name!("Ryan")
#查詢多個(gè)字段
Client.find_by_name_and_locked("Ryan", true)
#查詢不到時(shí)就創(chuàng)建并保存
Client.find_or_create_by_name(params[:name])
#查詢不到時(shí)創(chuàng)建一個(gè)實(shí)例,但不保存
Client.find_or_initialize_by_name('Ryan')
7、find_by_sql
復(fù)制代碼 代碼如下:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
8、select_all
和find_by_sql類似,但不會(huì)用model實(shí)例化返回記錄,你會(huì)得到一個(gè)hash數(shù)組
復(fù)制代碼 代碼如下:
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
9、判斷記錄是否存在
復(fù)制代碼 代碼如下:
#通過(guò)id來(lái)查詢
Client.exists?(1)
Client.exists?(1, 2, 3)
#or
Client.exists?([1,2,3])
#通過(guò)其他條件來(lái)查詢
Client.exists?(:conditions => "first_name = 'Ryan'")
#沒(méi)有參數(shù)時(shí),則:表是空的 ? false : true
Client.exists?
10、計(jì)算
復(fù)制代碼 代碼如下:
#求結(jié)果集條數(shù)
Client.count(:conditons => "first_name = 'Ryan'")
#求某個(gè)字段非空白的條數(shù)
Client.count(:age)
#平均值
Client.average("orders_count")
#求最小值
Client.minimum("age")
#求最大值
Client.maximum("age")
#求和
Client.sum("orders_count")
您可能感興趣的文章:- Ruby連接使用windows下sql server數(shù)據(jù)庫(kù)代碼實(shí)例
- 在Ruby程序中連接數(shù)據(jù)庫(kù)的詳細(xì)教程
- Ruby中訪問(wèn)SQL Server數(shù)據(jù)庫(kù)的配置實(shí)例
- ruby+nokogori抓取糗事百科前10頁(yè)并存儲(chǔ)進(jìn)數(shù)據(jù)庫(kù)示例
- 淺談Ruby on Rails下的rake與數(shù)據(jù)庫(kù)數(shù)據(jù)遷移操作