Ruby on rails 如何在Rails中插入一组ActiveRecord对象和关系?

Ruby on rails 如何在Rails中插入一组ActiveRecord对象和关系?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我正在使用一个提供公交车到达数据的API。对于每一个请求,我都会得到(除其他事项外)一个列表,列出哪些路线服务于所讨论的站点。例如,如果列表中包含公交线路#1、2和5的结果,那么我知道这些服务于该站 我在Route和Stop之间建立了多对多关系,我希望在每个请求中动态检查和更新这些关联。没有哪条路线为哪一站服务的“主列表”,因此这似乎是获取此数据的最佳方式 我相信我现在的做法效率很低: # routes is an array of [number, destination] that I bu

我正在使用一个提供公交车到达数据的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
#routes是我在迭代数据时构建的[number,destination]数组
routes.uniq.每个do | route|
编号=路线[0]
目的地=路线[1]
r=路线。通过编号和目的地(编号,目的地)查找
如果!R
r=Route.new:number=>number,:destination=>destination
r、 拯救
结束
#我必须检查它是否已经存在,因为我找不到方法
#使用2个外键在联接表上创建唯一性约束的步骤
r、 停止如果我做对了,你应该有两个型号。路线模型和站点模型

以下是我将如何定义这些模型:

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
最后,我将使用以下代码:

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

r = Route.find(number)
r.destination_id = destination
r.stops << stop
#首先,查找所有相关路由,仅用于缓存。
路线。查找(编号)
r=路线。查找(编号)
r、 目的地\标识=目的地

r、 stops可能有一个很好的方法来清理stops调用,但是假设我正确地描述了路由的结构,那么这会清理很多

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
routes.uniq.each do |编号,目的地|
r=路线。通过编号和目的地查找或创建路线(路线[0],目的地)
r、 停止尝试此宝石:

文档说它比查找或创建快80%

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