2008-09-07 45 views
2

我正在使用提供公交車到達數據的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)添加一個關係到當前停止,如果它不存在。

有沒有更好的方法來做到這一點,例如通過在內存中獲取一堆數據並在應用服務器端進行一些處理,以避免我目前正在執行的大量數據庫調用?

回答

1

如果我理解正確,您(應該)有2個模型。路線模型和停止模型。

這是我如何定義這些模式:

class Route < ActiveRecord::Base 
    has_and_belongs_to_many :stops 
    belongs_to :stop, :foreign_key => 'destination_id' 
end 

class Stop < ActiveRecorde::Base 
    has_and_belongs_to_many :routes 
end 

而這裏的我會怎樣設置我的表:

create_table :routes do |t| 
    t.integer :destination_id 
    # Any other information you want to store about routes 
end 

create_table :stops do |t| 
    # Any other information you want to store about stops 
end 

create_table :routes_stops, :primary_key => [:route_id, :stop_id] do |t| 
    t.integer :route_id 
    t.integer :stop_id 
end 

最後,這裏的代碼,我會用:

# First, find all the relevant routes, just for caching. 
Route.find(numbers) 

r = Route.find(number) 
r.destination_id = destination 
r.stops << stop 

這應該只使用一些SQL查詢。

0

清理停靠點呼叫可能是一種很好的方法,但這會清理它,假設我正確地描繪了路線的結構。

routes.uniq.each do |number, destination| 

    r = Route.find_or_create_by_number_and_destination(route[0], destination) 

    r.stops << stop unless r.stops.include? stop 

end 
相關問題