[英]Inserting into DB from data in Hash and Arrays
I have defined my hash and arrays like this: 我已经定义了我的哈希和数组,如下所示:
POPULATION_SUMMARIES = {
'ACO' => [ # year , member_count
[2013, 523031],
[2012, 492349],
[2011, 432573]
]
}
So the table I want to insert into is PopulationSummary . 因此,我要插入的表是PopulationSummary 。 And its row/fields are like this:
它的行/字段是这样的:
ACO, 2013, 523031
ACO, 2012, 492349
ACO, 2011, 432573
Org_id, year, member_count
In DB, It's actually the ID of those "ACO" or other stuff, they are basically foreign keys of another table.(ie. Organization table). 在DB中,它实际上是那些“ ACO”或其他内容的ID,它们基本上是另一个表(即组织表)的外键。
So I am trying to loop through this and read the structure and write it in the table. 因此,我尝试遍历此过程,并读取结构并将其写入表中。 I went as far as something like this:
我走到了这样的程度:
POPULATION_SUMMARIES.each do |k, v|
org_id = Organization.find_by_name(k).id # so for example ID of ACO
v.each do |o| # now read elements of each array
# HERE :( QUESTION
end
end
So the part I am having trouble with is how to say Ok the first number you read from the array, insert it for the year field, the second number you read from the table: insert it for member_count field.... 因此,我遇到的问题是如何说好,从数组中读取的第一个数字插入到Year字段中,从表中读取的第二个数字插入:在member_count字段中插入...。
This should get you close: 这应该使您接近:
POPULATION_SUMMARIES.each do |org_name, summaries|
org = Organization.find_or_create_by_name(org_name)
summaries.each do |year, member_count|
PopulationSummary.create({
:organization => org,
:year => year,
:member_count => member_count
})
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.