【发布时间】:2008-09-07 08:10:00
【问题描述】:
我正在使用一个提供巴士到达数据的 API。对于每个请求,我都会(除其他外)返回一个列表,其中列出了哪些路线服务于相关站点。例如,如果列表中包含公交路线 #1、2 和 5 的结果,那么我知道那些服务于该站点。
我在 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) 如果它不存在,则添加到当前停靠点的关系。
有没有更好的方法来做到这一点,例如通过在内存中获取一堆数据并在应用服务器端进行一些处理,以避免我目前正在进行的大量数据库调用?
【问题讨论】:
标签: ruby-on-rails activerecord