2017-01-30 106 views
0

我有一个研究所和一个位置表。我从提取电子表格中的数据,目前有如下信息:从栏表参考中获取外键

Institute 

id, name, ukprn 

Location 

id, name, ukprn, lat, long, institute 

ukprn是通过政府给予的唯一的ID,但在未来的某个机构可能没有这个,所以我不想具体使用作为参考。我认为我需要做的是让Location.institute属性包含Institute.ukprn和Location.ukprn匹配的Institute.id,但我不确定这将如何工作并将其保存到代码中。

我想:

Location.each do |location| 
    if location.ukprn == Institute.ukprn then 
    put Institute.id => Location.institute 
    end 
end 

这想出了一个未定义的方法 '每个' 错误。我显然做错了什么,但不知道如何去做这件事。

回答

1

你会得到undefined method each error,因为位置作为模型类没有每种方法。还有其他的东西在你的代码中是错误的。

你必须这样做以如下方式,

Institute.find_each do |institute| 
    Location.where(ukprn: institute.ukprn).update_all(institute_id: institute.id) 
end 

在上面的代码为你检查对应于所有位置ukprn每个机构,每个匹配的位置的institute_id将与学院ID更新。

+1

你可以考虑使用find_each而不是all.each。这样它将会更快,并且在运行时会占用更少的内存。 –

+0

@SatyamSingh是的。你是对的。更新了我的答案。 – dnsh

+0

这是完美的。感谢代码和解释家伙! –

0

调用每个类的方法没有任何意义。首先让所有的地点和机构,做一些象下面这样:

@locations = Location.all 
@institutes = Institute.all 

@locations.each do |location| 
    @institutes.each do |institute| 
    if location.ukprn == institute.ukprn 
    institute.id = location.institute 
    institute.save! 
    end 
    end 
end 

我猜有可能是一个更好的方式,不使用每个遍历每个记录,如优化查询,你可以删除/关口记录为“已处理”,然后再获取“未处理”记录,以便在后续的each循环中减小阵列大小。

希望它有帮助!让我知道你是否看起来像这样。