简体   繁体   中英

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 . 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).

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....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM