我正在使用提供公交車到達數據的API。對於每一個請求,我都會返回(除其他事項外)列出哪些路線服務於所涉及的站點。例如,如果列表包含公交路線#1,2和5的結果,那麼我知道那些服務於此站點。如何在Rails中插入一堆ActiveRecord對象和關係?
我在Route和Stop之間建立了多對多的關係,我想在每個請求中動態檢查和更新這些關聯。沒有哪個路線服務哪個站點的「主列表」,所以這似乎是獲取這些數據的最佳方式。
我相信,我現在做的方式是非常低效的:
# routes is an array of [number, destination] that I build while iterating over the data
routes.uniq.each do |route|
number = route[0]
destination = route[1]
r = Route.find_by_number_and_destination(number, destination)
if !r
r = Route.new :number => number, :destination => destination
r.save
end
# I have to check if it already exists because I can't find a way
# to create a uniqueness constraint on the join table with 2 foreign keys
r.stops << stop unless r.stops.include? stop
end
基本上,我得爲每一次我發現路由做兩兩件事: 1)創建它,如果它不已經存在,2)添加一個關係到當前停止,如果它不存在。
有沒有更好的方法來做到這一點,例如通過在內存中獲取一堆數據並在應用服務器端進行一些處理,以避免我目前正在執行的大量數據庫調用?
更快的80%它的速度更快,只要你在 「批」 模式下使用它... – 2012-07-05 14:13:48