我有一張名爲Staging
的表格,其中放置了Excel電子表格中的所有數據,通過查找現有模型/表格獲取ID號碼,然後比較它與當前數據庫是SQL Server 2008的在Ruby on Rails中加速find_by搜索
我的代碼如下:
def compare
require 'rubygems'
require 'spreadsheet'
require 'set'
Spreadsheet.client_encoding = 'UTF-8'
file_full_path = File.expand_path(File.join(File.dirname(__FILE__), "../../SISlist.xls"))
book = Spreadsheet.open(file_full_path) #Select excel file
sheet = book.worksheet 0 #Select 1st worksheet
app,server,env = 0
for i in 1..500
row = sheet.row(i)
if row[0].to_s != "" # Makes sure no empty cells are saved
row.each do |t|
app = App.find_by_name(row[0].to_s)
server = Server.find_by_name(row[2].to_s)
env = Environment.find_by_code(row[3].to_s)
end
Staging.create(:app => app.id, :server => server.id, :environment => env.id)
end
end
end
我現在遇到的問題是,它需要很長的執行這個方法(差不多20秒) ,當我所有其他類似的方法都沒有那麼長時間。
任何加快這個過程的方法,或者我的工作流程是不正確的,因此整個架構是錯誤的?
幫助需要
您可能可以使用[批量查找](http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find) – jaydel
@jaydel會與RoR 3合作?因爲它說2.3,所以它可能會貶值? – omarArroum
是的,它是如此。對不良鏈接抱歉。這裏有一個更好的 - 一個偉大的[指南](http://guides.rubyonrails.org/active_record_querying.html) – jaydel